-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 posts ] 
Author Message
 Post subject: Problem with hbm2java: Could not resolve type
PostPosted: Wed Feb 07, 2007 8:52 pm 
Newbie

Joined: Wed Feb 07, 2007 7:13 pm
Posts: 5
It threw this exception when I tried to generate POJO directly from database, it failed to get the JavaRawType for a foreign key column(one to many) and the exception suggested that the courtpart property.value of this column is null, appreciate your help.

I am using Hibernate 3.2.0 and the tool library compiled from the source in Hibernate SVN.

[java] freemarker.template.TemplateModelException: Method public java.lang.String org.hibernate.tool.hbm2
x.pojo.BasicPOJOClass.getJavaTypeName(org.hibernate.mapping.Property,boolean) threw an exception when invoked
on org.hibernate.tool.hbm2x.pojo.EntityPOJOClass(AdColumn)
[java] at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:136)
[java] at freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:93)
[java] at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
[java] at freemarker.core.Expression.getStringValue(Expression.java:93)
[java] at freemarker.core.DollarVariable.accept(DollarVariable.java:76)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.ConditionalBlock.accept(ConditionalBlock.java:79)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:160)
[java] at freemarker.core.Environment.visit(Environment.java:351)
[java] at freemarker.core.IteratorBlock.accept(IteratorBlock.java:95)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.Environment.include(Environment.java:1375)
[java] at freemarker.core.Include.accept(Include.java:155)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.IfBlock.accept(IfBlock.java:82)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.Environment.visit(Environment.java:233)
[java] at freemarker.core.BlockAssignment.accept(BlockAssignment.java:83)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[java] at freemarker.core.Environment.visit(Environment.java:196)
[java] at freemarker.core.Environment.process(Environment.java:176)
[java] at freemarker.template.Template.process(Template.java:232)
[java] at generator.AppGenerator.exportPOJOFile(AppGenerator.java:218)
[java] at generator.AppGenerator.exportPOJOClass(AppGenerator.java:190)
[java] at generator.AppGenerator.main(AppGenerator.java:113)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[java] at java.lang.reflect.Method.invoke(Method.java:597)
[java] at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
[java] at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
[java] at org.apache.tools.ant.taskdefs.Java.run(Java.java:747)
[java] at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:201)
[java] at org.apache.tools.ant.taskdefs.Java.execute(Java.java:104)
[java] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[java] at java.lang.reflect.Method.invoke(Method.java:597)
[java] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105)
[java] at org.apache.tools.ant.Task.perform(Task.java:348)
[java] at org.apache.tools.ant.Target.execute(Target.java:357)
[java] at org.apache.tools.ant.Target.performTasks(Target.java:385)
[java] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329)
[java] at org.apache.tools.ant.Project.executeTarget(Project.java:1298)
[java] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[java] at org.apache.tools.ant.Project.executeTargets(Project.java:1181)
[java] at org.apache.tools.ant.Main.runBuild(Main.java:698)
[java] at org.apache.tools.ant.Main.startAnt(Main.java:199)
[java] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)
[java] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)
[java] Caused by: org.hibernate.tool.hbm2x.ExporterException: Could not resolve type without exception fo
r org.hibernate.mapping.Property(adAccesslogs) Value: org.hibernate.mapping.Set(AdColumn.adAccesslogs)
[java] at org.hibernate.tool.hbm2x.Cfg2JavaTool.getRawTypeName(Cfg2JavaTool.java:279)
[java] at org.hibernate.tool.hbm2x.Cfg2JavaTool.getJavaTypeName(Cfg2JavaTool.java:180)
[java] at org.hibernate.tool.hbm2x.pojo.BasicPOJOClass.getJavaTypeName(BasicPOJOClass.java:815)
[java] at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[java] at java.lang.reflect.Method.invoke(Method.java:597)
[java] at freemarker.ext.beans.BeansWrapper.invokeMethod(BeansWrapper.java:825)
[java] at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:113)
[java] ... 60 more
[java] Caused by: java.lang.NullPointerException
[java] at org.hibernate.tool.hbm2x.visitor.JavaTypeFromValueVisitor.accept(JavaTypeFromValueVisitor.j
ava:43)
[java] at org.hibernate.mapping.OneToMany.accept(OneToMany.java:115)
[java] at org.hibernate.tool.hbm2x.Cfg2JavaTool.getJavaTypeName(Cfg2JavaTool.java:301)
[java] at org.hibernate.tool.hbm2x.Cfg2JavaTool.getGenericCollectionDeclaration(Cfg2JavaTool.java:286
)
[java] at org.hibernate.tool.hbm2x.Cfg2JavaTool.getRawTypeName(Cfg2JavaTool.java:263)
[java] ... 67 more





And I was used my customized code to call the exporter:


package generator;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.JDBCMetaDataConfiguration;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.MetaAttributable;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.tool.hbm2x.Cfg2HbmTool;
import org.hibernate.tool.hbm2x.ConfigurationNavigator;
import org.hibernate.tool.hbm2x.pojo.ComponentPOJOClass;
import org.hibernate.tool.hbm2x.pojo.POJOClass;
import org.hibernate.type.CharacterType;
import org.hibernate.type.StringType;

/**
* The local thread hold variable for the whole application scope
*
*
*/
public class AppGenerator {
private static Log log = LogFactory.getLog(AppGenerator.class);

GeneratorHelper c2j;
JDBCMetaDataConfiguration cfg;
Connection con;
Configuration freemarker;
String dest;

@SuppressWarnings("unchecked")
Map data = new HashMap();

@SuppressWarnings("unchecked")
public AppGenerator(String templateDir, String dest) {

freemarker = new Configuration();
try {
freemarker.setDirectoryForTemplateLoading(new File(templateDir));
} catch (IOException e) {
log.error("Can't find the template path", e);
}
freemarker.setObjectWrapper(new DefaultObjectWrapper());

this.dest = dest;

c2j = new GeneratorHelper();
cfg = new JDBCMetaDataConfiguration();
cfg.configure();
con = cfg.buildSessionFactory().openSession().connection();
cfg.readFromJDBC();

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
data.put("date", format.format(new Date()));
data.put("version", "1.0");
data.put("jdk5", true);
data.put("ejb3", true);
data.put("generics",true);
data.put("c2j", c2j);
data.put("c2h", new Cfg2HbmTool());
}

public static void main(String[] args) {

AppGenerator generator = new AppGenerator("C:/Program Files/Java/workspace/adempiere/etc/templates",
"C:/Program Files/Java/workspace/adempiere/src");

try {

PreparedStatement clm = generator.con
.prepareStatement("SELECT c.ad_column_id, c.name, c.description, c.help, c.defaultvalue, c.AD_Reference_ID, c.AD_Reference_value_ID "
+ "FROM ad_column c, ad_table t where tablename=? and columnname=? and t.ad_table_id = c.ad_table_id ");

PreparedStatement fld = generator.con
.prepareStatement("SELECT f.seqno, f.isdisplayed, f.isreadonly,f.issameline, f.ad_fieldgroup_id FROM ad_field f where f.ad_column_id=? ");

Iterator iterator = generator.c2j.getPOJOIterator(generator.cfg.getClassMappings());
ArrayList e = new ArrayList();
String packagename;
while (iterator.hasNext()) {
POJOClass element = (POJOClass) iterator.next();

if ("AdColumn".equals(element.getDeclarationName()) || "AdMenu".equals(element.getDeclarationName()) ) {
packagename = element.getDeclarationName();
packagename = "domain.ad." + packagename.substring(0, 1).toLowerCase() + packagename.substring(1);

log.info("start set attributes.....");
generator.setApplicationAttributes(element, packagename, clm, fld);
log.info("end set attributes!");

generator.exportPOJOClass(element);
generator.exportJavaFile(element, "struts/ebForm.ftl", "EbForm");
generator.exportJavaFile(element, "struts/Form.ftl", "Form");
generator.exportJavaFile(element, "struts/Action.ftl", "Action");
generator.exportJavaFile(element, "struts/Service.ftl", "Service");
generator.exportJavaFile(element, "struts/ServiceImpl.ftl", "JPAImpl");

generator.exportJSPFile(element, "jsp/Search.ftl", "Search");
generator.exportJSPFile(element, "jsp/ebSearch.ftl", "EbSearch");
generator.exportJSPFile(element, "jsp/Detail.ftl", "Detail");
generator.exportJSPFile(element, "jsp/ebDetail.ftl", "EbDetail");

e.add(element);
}
}
clm.close();
fld.close();
generator.con.close();

generator.exportConfigFile(e, "etc/StrutsConfig.ftl", "struts-config.xml");
generator.exportConfigFile(e, "etc/sun-jaxws.ftl", "sun-jaxws.xml");
} catch (Exception e) {
log.error("Failed to generate file", e);
} finally {
try {
generator.con.close();
generator.cfg = null;
} catch (Exception e1) {
}
}
}

@SuppressWarnings("unchecked")
private void exportConfigFile(ArrayList e, String t, String targetFile) throws TemplateException, IOException {

data.put("pojos", e);

File f = new File(dest);
f.mkdirs();
FileWriter out = new FileWriter(new File(f, targetFile));

log.info("Generating " + targetFile);
Template temp = freemarker.getTemplate(t);
temp.process(data, out);
out.close();
}

private void exportJavaFile(POJOClass element, String t, String suffix) throws TemplateException, IOException {

data.put("pojo", element);
data.put("clazz", element.getDecoratedObject());

File f = new File(dest + "/java/" + element.getPackageName().replace(".", "/"));
f.mkdirs();
FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + suffix + ".java"));

Template temp = freemarker.getTemplate(t);
temp.process(data, out);
out.close();
}

private void exportJSPFile(POJOClass element, String t, String suffix) throws TemplateException, IOException {

data.put("pojo", element);

File f = new File(dest + "/jsp/" + element.getPackageName().replace(".", "/"));
f.mkdirs();
FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + suffix + ".jsp"));

Template temp = freemarker.getTemplate(t);
temp.process(data, out);
out.close();
}

@SuppressWarnings( { "unchecked", "unchecked" })
public void exportPOJOClass(POJOClass element) throws Exception {

exportPOJOFile(element, data);
String packagename = element.getPackageName();

// Expoert the component class(Primary key) of this class
Map keys = new HashMap();
ConfigurationNavigator.collectComponents(keys, element);
Iterator ki = keys.values().iterator();
while (ki.hasNext()) {
Component component = (Component) ki.next();

// change the package name to the same one as the parent
component.setComponentClassName(packagename + "." + component.getComponentClassName());

element = new ComponentPOJOClass(component, c2j);
exportPOJOFile(element, data);
}
}

@SuppressWarnings("unchecked")
private void exportPOJOFile(POJOClass element, Map args) throws TemplateException, IOException {
args.put("pojo", element);
args.put("clazz", element.getDecoratedObject());

File f = new File(dest + "/java/" + element.getPackageName().replace(".", "/"));
f.mkdirs();
FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + ".java"));

Template temp = freemarker.getTemplate("pojo/Pojo.ftl");
temp.process(args, out);
out.close();
}

@SuppressWarnings("unchecked")
public void setApplicationAttributes(POJOClass element, String packagename, PreparedStatement clm,
PreparedStatement fld) throws Exception {

PersistentClass persistent = (PersistentClass) element.getDecoratedObject();
// modify the default package name
setMetaAttribute(persistent, "generated-class", packagename+"." + persistent.getClassName());

clm.setString(1, persistent.getTable().getName());
Iterator iterator = persistent.getPropertyIterator();
Column column;
Property property;
ResultSet rs;
while (iterator.hasNext()) {
property = (Property) iterator.next();
if (property.getColumnSpan() == 1 && property.getColumnIterator().hasNext()) {
column = (Column) property.getColumnIterator().next();

clm.setString(2, column.getName());
rs = clm.executeQuery();
if (rs.next()) {
// Add field description
setMetaAttribute(property, "field-description", rs.getString("description") + ".\r\n"
+ rs.getString("help"));

// add default value
String defaultValue = rs.getString("defaultvalue");
if (column.getDefaultValue() == null && defaultValue != null && !defaultValue.startsWith("@")) {// default-value

if (property.getType() instanceof CharacterType) {
defaultValue = "'" + defaultValue + "'";
} else if (property.getType() instanceof StringType) {
defaultValue = "\"" + defaultValue + "\"";
}
setMetaAttribute(property, "default-value", defaultValue);
}
addMetaAttribute(property, "label", rs, "name");
addMetaAttribute(property, "reference", rs, "AD_Reference_ID");
addMetaAttribute(property, "reference_value", rs, "AD_Reference_value_ID");
addMetaAttribute(property, "column_id", rs, "ad_column_id");
}
rs.close();
}
}

// get other attributes, application specified
iterator = persistent.getPropertyIterator();
while (iterator.hasNext()) {
property = (Property) iterator.next();

fld.setInt(1, c2j.getMetaAsInt(property, "column_id"));

rs = fld.executeQuery();
if (rs.next()) {
addMetaAttribute(property, "isdisplayed", rs, "isdisplayed");
addMetaAttribute(property, "seqno", rs, "seqno");
addMetaAttribute(property, "issameline", rs, "issameline");
addMetaAttribute(property, "isreadonly", rs, "isreadonly");
addMetaAttribute(property, "fieldgroup", rs, "ad_fieldgroup_id");
}
rs.close();
}
}

public void addMetaAttribute(MetaAttributable obj, String name, ResultSet rs, String column) throws SQLException {
setMetaAttribute(obj, name, rs.getString(column));
}

public void setMetaAttribute(MetaAttributable obj, String name, String value) {
if (value == null || "".equals(value))
return;

Map<String, MetaAttribute> metas = obj.getMetaAttributes() == null ? new HashMap() : obj.getMetaAttributes();

// Add a attribute meta
MetaAttribute meta = new MetaAttribute(name);
meta.addValue(value);
metas.put(name, meta);
obj.setMetaAttributes(metas);

}
}


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 08, 2007 5:57 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
i'm sorry, but your entry is not very readable. could you try and simplify it or at least use the proper mark up for code etc.

_________________
Max
Don't forget to rate


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 08, 2007 8:11 am 
Newbie

Joined: Wed Feb 07, 2007 7:13 pm
Posts: 5
I am sorry, repost the code here.

Code:
package generator;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.JDBCMetaDataConfiguration;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.MetaAttributable;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.tool.hbm2x.Cfg2HbmTool;
import org.hibernate.tool.hbm2x.ConfigurationNavigator;
import org.hibernate.tool.hbm2x.pojo.ComponentPOJOClass;
import org.hibernate.tool.hbm2x.pojo.POJOClass;
import org.hibernate.type.CharacterType;
import org.hibernate.type.StringType;

/**
* The local thread hold variable for the whole application scope
*
* @author kenvin
*
*/
public class AppGenerator {
   private static Log log = LogFactory.getLog(AppGenerator.class);

   GeneratorHelper c2j;
   JDBCMetaDataConfiguration cfg;
   Connection con;
   Configuration freemarker;
   String dest;

   @SuppressWarnings("unchecked")
   Map data = new HashMap();

   @SuppressWarnings("unchecked")
   public AppGenerator(String templateDir, String dest) {

      freemarker = new Configuration();
      try {
         freemarker.setDirectoryForTemplateLoading(new File(templateDir));
      } catch (IOException e) {
         log.error("Can't find the template path", e);
      }
      freemarker.setObjectWrapper(new DefaultObjectWrapper());

      this.dest = dest;

      c2j = new GeneratorHelper();
      cfg = new JDBCMetaDataConfiguration();
      cfg.configure();
      con = cfg.buildSessionFactory().openSession().connection();
      cfg.readFromJDBC();

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      data.put("date", format.format(new Date()));
      data.put("version", "1.0");
      data.put("jdk5", true);
      data.put("ejb3", true);
      data.put("generics", true);
      data.put("c2j", c2j);
      data.put("c2h", new Cfg2HbmTool());
   }

   public static void main(String[] args) {

      AppGenerator generator = new AppGenerator("C:/Program Files/Java/workspace/adempiere/etc/templates",
            "C:/Program Files/Java/workspace/adempiere/src");

      try {

         PreparedStatement clm = generator.con
               .prepareStatement("SELECT  c.ad_column_id, c.name, c.description, c.help, c.defaultvalue, c.AD_Reference_ID, c.AD_Reference_value_ID "
                     + "FROM ad_column c, ad_table t where tablename=? and  columnname=? and t.ad_table_id = c.ad_table_id ");

         PreparedStatement fld = generator.con
               .prepareStatement("SELECT  f.seqno, f.isdisplayed, f.isreadonly,f.issameline, f.ad_fieldgroup_id FROM ad_field f where f.ad_column_id=? ");

         Iterator<POJOClass> iterator = generator.c2j.getPOJOIterator(generator.cfg.getClassMappings());
         ArrayList e = new ArrayList();
         String packagename;
         while (iterator.hasNext()) {
            POJOClass element = (POJOClass) iterator.next();

            if ("AdColumn".equals(element.getDeclarationName()) || "AdMenu".equals(element.getDeclarationName())) {
               packagename = element.getDeclarationName();
               packagename = "domain.ad." + packagename.substring(0, 1).toLowerCase() + packagename.substring(1);

               log.info("start set attributes.....");
               generator.setApplicationAttributes(element, packagename, clm, fld);
               log.info("end set attributes!");

               generator.exportPOJOClass(element);
               generator.exportJavaFile(element, "struts/ebForm.ftl", "EbForm");
               generator.exportJavaFile(element, "struts/Form.ftl", "Form");
               generator.exportJavaFile(element, "struts/Action.ftl", "Action");
               generator.exportJavaFile(element, "struts/Service.ftl", "Service");
               generator.exportJavaFile(element, "struts/ServiceImpl.ftl", "JPAImpl");

               generator.exportJSPFile(element, "jsp/Search.ftl", "Search");
               generator.exportJSPFile(element, "jsp/ebSearch.ftl", "EbSearch");
               generator.exportJSPFile(element, "jsp/Detail.ftl", "Detail");
               generator.exportJSPFile(element, "jsp/ebDetail.ftl", "EbDetail");

               e.add(element);
            }
         }
         clm.close();
         fld.close();
         generator.con.close();

         generator.exportConfigFile(e, "etc/StrutsConfig.ftl", "struts-config.xml");
         generator.exportConfigFile(e, "etc/sun-jaxws.ftl", "sun-jaxws.xml");
      } catch (Exception e) {
         log.error("Failed to generate file", e);
      } finally {
         try {
            generator.con.close();
            generator.cfg = null;
         } catch (Exception e1) {
         }
      }
   }

   @SuppressWarnings("unchecked")
   private void exportConfigFile(ArrayList e, String t, String targetFile) throws TemplateException, IOException {

      data.put("pojos", e);

      File f = new File(dest);
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, targetFile));

      log.info("Generating " + targetFile);
      Template temp = freemarker.getTemplate(t);
      temp.process(data, out);
      out.close();
   }

   private void exportJavaFile(POJOClass element, String t, String suffix) throws TemplateException, IOException {

      data.put("pojo", element);
      data.put("clazz", element.getDecoratedObject());

      File f = new File(dest + "/java/" + element.getPackageName().replace(".", "/"));
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + suffix + ".java"));

      Template temp = freemarker.getTemplate(t);
      temp.process(data, out);
      out.close();
   }

   private void exportJSPFile(POJOClass element, String t, String suffix) throws TemplateException, IOException {

      data.put("pojo", element);

      File f = new File(dest + "/jsp/" + element.getPackageName().replace(".", "/"));
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + suffix + ".jsp"));

      Template temp = freemarker.getTemplate(t);
      temp.process(data, out);
      out.close();
   }

   @SuppressWarnings( { "unchecked", "unchecked" })
   public void exportPOJOClass(POJOClass element) throws Exception {

      exportPOJOFile(element, data);
      String packagename = element.getPackageName();

      // Expoert the component class(Primary key) of this class
      Map keys = new HashMap();
      ConfigurationNavigator.collectComponents(keys, element);
      Iterator ki = keys.values().iterator();
      while (ki.hasNext()) {
         Component component = (Component) ki.next();

         // change the package name to the same one as the parent
         component.setComponentClassName(packagename + "." + component.getComponentClassName());

         element = new ComponentPOJOClass(component, c2j);
         exportPOJOFile(element, data);
      }
   }

   @SuppressWarnings("unchecked")
   private void exportPOJOFile(POJOClass element, Map args) throws TemplateException, IOException {
      args.put("pojo", element);
      args.put("clazz", element.getDecoratedObject());

      File f = new File(dest + "/java/" + element.getPackageName().replace(".", "/"));
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + ".java"));

      Template temp = freemarker.getTemplate("pojo/Pojo.ftl");
      temp.process(args, out);
      out.close();
   }

   @SuppressWarnings("unchecked")
   public void setApplicationAttributes(POJOClass element, String packagename, PreparedStatement clm,
         PreparedStatement fld) throws Exception {

      PersistentClass persistent = (PersistentClass) element.getDecoratedObject();
      // modify the default package name
      setMetaAttribute(persistent, "generated-class", packagename + "." + persistent.getClassName());

      clm.setString(1, persistent.getTable().getName());
      Iterator iterator = persistent.getPropertyIterator();
      Column column;
      Property property;
      ResultSet rs;
      while (iterator.hasNext()) {
         property = (Property) iterator.next();
         if (property.getColumnSpan() == 1 && property.getColumnIterator().hasNext()) {
            column = (Column) property.getColumnIterator().next();

            clm.setString(2, column.getName());
            rs = clm.executeQuery();
            if (rs.next()) {
               // Add field description
               setMetaAttribute(property, "field-description", rs.getString("description") + ".\r\n"
                     + rs.getString("help"));

               // add default value
               String defaultValue = rs.getString("defaultvalue");
               if (column.getDefaultValue() == null && defaultValue != null && !defaultValue.startsWith("@")) {// default-value

                  if (property.getType() instanceof CharacterType) {
                     defaultValue = "'" + defaultValue + "'";
                  } else if (property.getType() instanceof StringType) {
                     defaultValue = "\"" + defaultValue + "\"";
                  }
                  setMetaAttribute(property, "default-value", defaultValue);
               }
               addMetaAttribute(property, "label", rs, "name");
               addMetaAttribute(property, "reference", rs, "AD_Reference_ID");
               addMetaAttribute(property, "reference_value", rs, "AD_Reference_value_ID");
               addMetaAttribute(property, "column_id", rs, "ad_column_id");
            }
            rs.close();
         }
      }

      // get other attributes, application specified
      iterator = persistent.getPropertyIterator();
      while (iterator.hasNext()) {
         property = (Property) iterator.next();

         fld.setInt(1, c2j.getMetaAsInt(property, "column_id"));

         rs = fld.executeQuery();
         if (rs.next()) {
            addMetaAttribute(property, "isdisplayed", rs, "isdisplayed");
            addMetaAttribute(property, "seqno", rs, "seqno");
            addMetaAttribute(property, "issameline", rs, "issameline");
            addMetaAttribute(property, "isreadonly", rs, "isreadonly");
            addMetaAttribute(property, "fieldgroup", rs, "ad_fieldgroup_id");
         }
         rs.close();
      }
   }

   public void addMetaAttribute(MetaAttributable obj, String name, ResultSet rs, String column) throws SQLException {
      setMetaAttribute(obj, name, rs.getString(column));
   }

   public void setMetaAttribute(MetaAttributable obj, String name, String value) {
      if (value == null || "".equals(value))
         return;

      Map<String, MetaAttribute> metas = obj.getMetaAttributes() == null ? new HashMap() : obj.getMetaAttributes();

      // Add a attribute meta
      MetaAttribute meta = new MetaAttribute(name);
      meta.addValue(value);
      metas.put(name, meta);
      obj.setMetaAttributes(metas);

   }
}


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 08, 2007 8:12 am 
Newbie

Joined: Wed Feb 07, 2007 7:13 pm
Posts: 5
I am sorry, repost the code here.

Code:
package generator;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.JDBCMetaDataConfiguration;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.MetaAttributable;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.tool.hbm2x.Cfg2HbmTool;
import org.hibernate.tool.hbm2x.ConfigurationNavigator;
import org.hibernate.tool.hbm2x.pojo.ComponentPOJOClass;
import org.hibernate.tool.hbm2x.pojo.POJOClass;
import org.hibernate.type.CharacterType;
import org.hibernate.type.StringType;

/**
* The local thread hold variable for the whole application scope
*
* @author kenvin
*
*/
public class AppGenerator {
   private static Log log = LogFactory.getLog(AppGenerator.class);

   GeneratorHelper c2j;
   JDBCMetaDataConfiguration cfg;
   Connection con;
   Configuration freemarker;
   String dest;

   @SuppressWarnings("unchecked")
   Map data = new HashMap();

   @SuppressWarnings("unchecked")
   public AppGenerator(String templateDir, String dest) {

      freemarker = new Configuration();
      try {
         freemarker.setDirectoryForTemplateLoading(new File(templateDir));
      } catch (IOException e) {
         log.error("Can't find the template path", e);
      }
      freemarker.setObjectWrapper(new DefaultObjectWrapper());

      this.dest = dest;

      c2j = new GeneratorHelper();
      cfg = new JDBCMetaDataConfiguration();
      cfg.configure();
      con = cfg.buildSessionFactory().openSession().connection();
      cfg.readFromJDBC();

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      data.put("date", format.format(new Date()));
      data.put("version", "1.0");
      data.put("jdk5", true);
      data.put("ejb3", true);
      data.put("generics", true);
      data.put("c2j", c2j);
      data.put("c2h", new Cfg2HbmTool());
   }

   public static void main(String[] args) {

      AppGenerator generator = new AppGenerator("C:/Program Files/Java/workspace/adempiere/etc/templates",
            "C:/Program Files/Java/workspace/adempiere/src");

      try {

         PreparedStatement clm = generator.con
               .prepareStatement("SELECT  c.ad_column_id, c.name, c.description, c.help, c.defaultvalue, c.AD_Reference_ID, c.AD_Reference_value_ID "
                     + "FROM ad_column c, ad_table t where tablename=? and  columnname=? and t.ad_table_id = c.ad_table_id ");

         PreparedStatement fld = generator.con
               .prepareStatement("SELECT  f.seqno, f.isdisplayed, f.isreadonly,f.issameline, f.ad_fieldgroup_id FROM ad_field f where f.ad_column_id=? ");

         Iterator<POJOClass> iterator = generator.c2j.getPOJOIterator(generator.cfg.getClassMappings());
         ArrayList e = new ArrayList();
         String packagename;
         while (iterator.hasNext()) {
            POJOClass element = (POJOClass) iterator.next();

            if ("AdColumn".equals(element.getDeclarationName()) || "AdMenu".equals(element.getDeclarationName())) {
               packagename = element.getDeclarationName();
               packagename = "domain.ad." + packagename.substring(0, 1).toLowerCase() + packagename.substring(1);

               log.info("start set attributes.....");
               generator.setApplicationAttributes(element, packagename, clm, fld);
               log.info("end set attributes!");

               generator.exportPOJOClass(element);
               generator.exportJavaFile(element, "struts/ebForm.ftl", "EbForm");
               generator.exportJavaFile(element, "struts/Form.ftl", "Form");
               generator.exportJavaFile(element, "struts/Action.ftl", "Action");
               generator.exportJavaFile(element, "struts/Service.ftl", "Service");
               generator.exportJavaFile(element, "struts/ServiceImpl.ftl", "JPAImpl");

               generator.exportJSPFile(element, "jsp/Search.ftl", "Search");
               generator.exportJSPFile(element, "jsp/ebSearch.ftl", "EbSearch");
               generator.exportJSPFile(element, "jsp/Detail.ftl", "Detail");
               generator.exportJSPFile(element, "jsp/ebDetail.ftl", "EbDetail");

               e.add(element);
            }
         }
         clm.close();
         fld.close();
         generator.con.close();

         generator.exportConfigFile(e, "etc/StrutsConfig.ftl", "struts-config.xml");
         generator.exportConfigFile(e, "etc/sun-jaxws.ftl", "sun-jaxws.xml");
      } catch (Exception e) {
         log.error("Failed to generate file", e);
      } finally {
         try {
            generator.con.close();
            generator.cfg = null;
         } catch (Exception e1) {
         }
      }
   }

   @SuppressWarnings("unchecked")
   private void exportConfigFile(ArrayList e, String t, String targetFile) throws TemplateException, IOException {

      data.put("pojos", e);

      File f = new File(dest);
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, targetFile));

      log.info("Generating " + targetFile);
      Template temp = freemarker.getTemplate(t);
      temp.process(data, out);
      out.close();
   }

   private void exportJavaFile(POJOClass element, String t, String suffix) throws TemplateException, IOException {

      data.put("pojo", element);
      data.put("clazz", element.getDecoratedObject());

      File f = new File(dest + "/java/" + element.getPackageName().replace(".", "/"));
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + suffix + ".java"));

      Template temp = freemarker.getTemplate(t);
      temp.process(data, out);
      out.close();
   }

   private void exportJSPFile(POJOClass element, String t, String suffix) throws TemplateException, IOException {

      data.put("pojo", element);

      File f = new File(dest + "/jsp/" + element.getPackageName().replace(".", "/"));
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + suffix + ".jsp"));

      Template temp = freemarker.getTemplate(t);
      temp.process(data, out);
      out.close();
   }

   @SuppressWarnings( { "unchecked", "unchecked" })
   public void exportPOJOClass(POJOClass element) throws Exception {

      exportPOJOFile(element, data);
      String packagename = element.getPackageName();

      // Expoert the component class(Primary key) of this class
      Map keys = new HashMap();
      ConfigurationNavigator.collectComponents(keys, element);
      Iterator ki = keys.values().iterator();
      while (ki.hasNext()) {
         Component component = (Component) ki.next();

         // change the package name to the same one as the parent
         component.setComponentClassName(packagename + "." + component.getComponentClassName());

         element = new ComponentPOJOClass(component, c2j);
         exportPOJOFile(element, data);
      }
   }

   @SuppressWarnings("unchecked")
   private void exportPOJOFile(POJOClass element, Map args) throws TemplateException, IOException {
      args.put("pojo", element);
      args.put("clazz", element.getDecoratedObject());

      File f = new File(dest + "/java/" + element.getPackageName().replace(".", "/"));
      f.mkdirs();
      FileWriter out = new FileWriter(new File(f, element.getDeclarationName() + ".java"));

      Template temp = freemarker.getTemplate("pojo/Pojo.ftl");
      temp.process(args, out);
      out.close();
   }

   @SuppressWarnings("unchecked")
   public void setApplicationAttributes(POJOClass element, String packagename, PreparedStatement clm,
         PreparedStatement fld) throws Exception {

      PersistentClass persistent = (PersistentClass) element.getDecoratedObject();
      // modify the default package name
      setMetaAttribute(persistent, "generated-class", packagename + "." + persistent.getClassName());

      clm.setString(1, persistent.getTable().getName());
      Iterator iterator = persistent.getPropertyIterator();
      Column column;
      Property property;
      ResultSet rs;
      while (iterator.hasNext()) {
         property = (Property) iterator.next();
         if (property.getColumnSpan() == 1 && property.getColumnIterator().hasNext()) {
            column = (Column) property.getColumnIterator().next();

            clm.setString(2, column.getName());
            rs = clm.executeQuery();
            if (rs.next()) {
               // Add field description
               setMetaAttribute(property, "field-description", rs.getString("description") + ".\r\n"
                     + rs.getString("help"));

               // add default value
               String defaultValue = rs.getString("defaultvalue");
               if (column.getDefaultValue() == null && defaultValue != null && !defaultValue.startsWith("@")) {// default-value

                  if (property.getType() instanceof CharacterType) {
                     defaultValue = "'" + defaultValue + "'";
                  } else if (property.getType() instanceof StringType) {
                     defaultValue = "\"" + defaultValue + "\"";
                  }
                  setMetaAttribute(property, "default-value", defaultValue);
               }
               addMetaAttribute(property, "label", rs, "name");
               addMetaAttribute(property, "reference", rs, "AD_Reference_ID");
               addMetaAttribute(property, "reference_value", rs, "AD_Reference_value_ID");
               addMetaAttribute(property, "column_id", rs, "ad_column_id");
            }
            rs.close();
         }
      }

      // get other attributes, application specified
      iterator = persistent.getPropertyIterator();
      while (iterator.hasNext()) {
         property = (Property) iterator.next();

         fld.setInt(1, c2j.getMetaAsInt(property, "column_id"));

         rs = fld.executeQuery();
         if (rs.next()) {
            addMetaAttribute(property, "isdisplayed", rs, "isdisplayed");
            addMetaAttribute(property, "seqno", rs, "seqno");
            addMetaAttribute(property, "issameline", rs, "issameline");
            addMetaAttribute(property, "isreadonly", rs, "isreadonly");
            addMetaAttribute(property, "fieldgroup", rs, "ad_fieldgroup_id");
         }
         rs.close();
      }
   }

   public void addMetaAttribute(MetaAttributable obj, String name, ResultSet rs, String column) throws SQLException {
      setMetaAttribute(obj, name, rs.getString(column));
   }

   public void setMetaAttribute(MetaAttributable obj, String name, String value) {
      if (value == null || "".equals(value))
         return;

      Map<String, MetaAttribute> metas = obj.getMetaAttributes() == null ? new HashMap() : obj.getMetaAttributes();

      // Add a attribute meta
      MetaAttribute meta = new MetaAttribute(name);
      meta.addValue(value);
      metas.put(name, meta);
      obj.setMetaAttributes(metas);

   }
}


Top
 Profile  
 
 Post subject:
PostPosted: Fri Feb 09, 2007 6:12 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
you have to reduce your code/problem to something smaller ;)

_________________
Max
Don't forget to rate


Top
 Profile  
 
 Post subject:
PostPosted: Sat Feb 10, 2007 6:25 am 
Newbie

Joined: Wed Feb 07, 2007 7:13 pm
Posts: 5
Max, thank you for your reply.

I can generate Java file by running your Ant task, but because I need to do a lots of customize to generate other kind of code. It seems I have missed something in my code that lead to the failure. I just wondering what else I need to do between the below code? Is the readFromJDBC() call will also resove all the Primary key and Foreign key and mapped them to the Hibernate meta?

Code:

cfg = new JDBCMetaDataConfiguration();
cfg.configure();
cfg.readFromJDBC();

Iterator<POJOClass> iterator = getPOJOIterator(generator.cfg.getClassMappings());
         
while (iterator.hasNext()) {
     POJOClass element = (POJOClass) iterator.next();
   
     //Do the exporter
}



Top
 Profile  
 
 Post subject:
PostPosted: Sat Feb 10, 2007 8:39 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
your code looks likeit is mixing up alot of stuff that i don't really see why you do those things in the exporter.

what ant task/code are you actually running?
Does it work/complete if you use the normal builtin exporters?

if no, then reduce the schema (i assume you are doing reveng) to the bare minimum where it stilll fails and submit that to jira so i can take a look.

_________________
Max
Don't forget to rate


Top
 Profile  
 
 Post subject:
PostPosted: Sat Feb 10, 2007 8:46 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
i reread your code and realize you basically just want to do alot of stuff "manually" instead of doing this via hbmtemplate's (i dont know why :)

anyway...my question about wether it work/comptere if you use the normal builtin exporters still stand......

_________________
Max
Don't forget to rate


Top
 Profile  
 
 Post subject:
PostPosted: Sat Feb 10, 2007 7:07 pm 
Newbie

Joined: Wed Feb 07, 2007 7:13 pm
Posts: 5
The normal builtin exporter is fine. But because I have store a lot of custom metadata in a table for generating code, and the total number of tables in the database is up to 600, I just don't want to retrieve the meta from the table and edit a huge hibernate.reveng.xml for 600 tables, that's why I have to do these stuff manually :). If a table doesn't have any foreign keys, it works, and will throw the exception when a table have foreign key. I trace the exception as far as I can , and found the code
in Cfg2JavaTool

Code:
private String getRawTypeName(Property p, boolean useGenerics, boolean preferRawTypeNames, ImportContext importContext) {
           Value value = p.getValue();

the value is null if the Property is a foreign key.


I run the below ant task for reveng without any problem, so I have really mixed up something in my code.

Code:

      <hibernatetool destdir="src" templatepath="etc/templates"  >
         <classpath>
            <path location="runtime.classpath"/>
         </classpath>

         <jdbcconfiguration configurationfile="etc/hibernate.cfg.xml"
              packagename="domain.ad"                           
              revengfile="etc/hibernate.reveng.xml"  detectmanytomany="true"      />
             
         <hbm2java jdk5="true" ejb3="true"/> 
         
      </hibernatetool> 
[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Sun Feb 11, 2007 1:18 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
kenvin9 wrote:
The normal builtin exporter is fine. But because I have store a lot of custom metadata in a table for generating code, and the total number of tables in the database is up to 600, I just don't want to retrieve the meta from the table and edit a huge hibernate.reveng.xml for 600 tables, that's why I have to do these stuff manually :).


Any reason why you don't write a custom revengStrategy that can weave in those meta attributes instead of this other more intrusive/redo-essential-parts approach ? ')

Quote:
If a table doesn't have any foreign keys, it works, and will throw the exception when a table have foreign key. I trace the exception as far as I can , and found the code
in Cfg2JavaTool

Code:
private String getRawTypeName(Property p, boolean useGenerics, boolean preferRawTypeNames, ImportContext importContext) {
           Value value = p.getValue();

the value is null if the Property is a foreign key.


eh - you mean if the Property is a many-to-one or ?

Quote:
I run the below ant task for reveng without any problem, so I have really mixed up something in my code.


something is definitly wrong somewhere...

_________________
Max
Don't forget to rate


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.