-->
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.  [ 1 post ] 
Author Message
 Post subject: hbm2dao
PostPosted: Tue Jan 15, 2008 11:21 am 
Newbie

Joined: Tue Jan 15, 2008 11:13 am
Posts: 1
Hi

I am trying to generate dao's using hbm2dao ant task. I have modified dao generation template little bit by referring some of the posts in this forum.

My problem is while generating dao's ant is showing the following error.

[hibernatetool] 2. task: hbm2java (Generates a set of .java files)
[hibernatetool] 3. task: generic exportertemplate: my-dao-template.ftl
[hibernatetool] (freemarker.runtime 96 )
[hibernatetool] Expression clazz.hasNaturalId is undefined on line 164, column 6 in my-dao-template.ftl.
[hibernatetool] The problematic instruction:
[hibernatetool] ----------
[hibernatetool] ==> if clazz.hasNaturalId() [on line 164, column 1 in my-dao-template.ftl]
[hibernatetool] ----------
[hibernatetool] Java backtrace for programmers:
[hibernatetool] ----------
[hibernatetool] freemarker.core.InvalidReferenceException: Expression clazz.hasNaturalId is undefined on line 164, column 6 in my-dao-template.ftl.
[hibernatetool] at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124)
[hibernatetool] at freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:134)
[hibernatetool] at freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:114)
[hibernatetool] at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
[hibernatetool] at freemarker.core.Expression.isTrue(Expression.java:138)
[hibernatetool] at freemarker.core.ConditionalBlock.accept(ConditionalBlock.java:77)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:196)
[hibernatetool] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:196)
[hibernatetool] at freemarker.core.IfBlock.accept(IfBlock.java:82)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:196)
[hibernatetool] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:196)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:233)
[hibernatetool] at freemarker.core.BlockAssignment.accept(BlockAssignment.java:83)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:196)
[hibernatetool] at freemarker.core.MixedContent.accept(MixedContent.java:92)
[hibernatetool] at freemarker.core.Environment.visit(Environment.java:196)
[hibernatetool] at freemarker.core.Environment.process(Environment.java:176)
[hibernatetool] at freemarker.template.Template.process(Template.java:232)
[hibernatetool] at org.hibernate.tool.hbm2x.TemplateHelper.processTemplate(TemplateHelper.java:251)
[hibernatetool] at org.hibernate.tool.hbm2x.TemplateProducer.produceToString(TemplateProducer.java:67)
[hibernatetool] at org.hibernate.tool.hbm2x.TemplateProducer.produce(TemplateProducer.java:28)
[hibernatetool] at org.hibernate.tool.hbm2x.TemplateProducer.produce(TemplateProducer.java:97)
[hibernatetool] at org.hibernate.tool.hbm2x.GenericExporter.exportPOJO(GenericExporter.java:146)
[hibernatetool] at org.hibernate.tool.hbm2x.GenericExporter.exportComponent(GenericExporter.java:131)
[hibernatetool] at org.hibernate.tool.hbm2x.GenericExporter$3.process(GenericExporter.java:61)
[hibernatetool] at org.hibernate.tool.hbm2x.GenericExporter.doStart(GenericExporter.java:126)
[hibernatetool] at org.hibernate.tool.hbm2x.AbstractExporter.start(AbstractExporter.java:95)
[hibernatetool] at org.hibernate.tool.ant.ExporterTask.execute(ExporterTask.java:40)
[hibernatetool] at org.hibernate.tool.ant.HibernateToolTask.execute(HibernateToolTask.java:186)
[hibernatetool] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
[hibernatetool] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[hibernatetool] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[hibernatetool] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[hibernatetool] at java.lang.reflect.Method.invoke(Method.java:585)
[hibernatetool] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105)
[hibernatetool] at org.apache.tools.ant.Task.perform(Task.java:348)
[hibernatetool] at org.apache.tools.ant.Target.execute(Target.java:357)
[hibernatetool] at org.apache.tools.ant.Target.performTasks(Target.java:385)
[hibernatetool] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329)
[hibernatetool] at org.apache.tools.ant.Project.executeTarget(Project.java:1298)
[hibernatetool] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[hibernatetool] at org.eclipse.ant.internal.ui.antsupport.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32)
[hibernatetool] at org.apache.tools.ant.Project.executeTargets(Project.java:1181)
[hibernatetool] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.run(InternalAntRunner.java:423)
[hibernatetool] at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.main(InternalAntRunner.java:137)
[hibernatetool] An exception occurred while running exporter #4:generic exportertemplate: my-dao-template.ftl
[hibernatetool] To get the full stack trace run ant with -verbose
[hibernatetool] org.hibernate.tool.hbm2x.ExporterException: Error while processing template my-dao-template.ftl
[hibernatetool] freemarker.core.InvalidReferenceException: Expression clazz.hasNaturalId is undefined on line 164, column 6 in my-dao-template.ftl.

BUILD FAILED
C:\ecs2008\htest\build.xml:61: org.hibernate.tool.hbm2x.ExporterException: Error while processing template my-dao-template.ftl


Here is the template:::::::::::::::::

${pojo.getPackageDeclaration()}
// Generated ${date} by Hibernate Tools ${version}

<#assign classbody>
<#assign declarationName = pojo.importType(pojo.getDeclarationName())>/**
* Home object for domain model class ${declarationName}.
* @see ${pojo.getQualifiedDeclarationName()}
* @author Hibernate Tools
*/
<#if ejb3>
@${pojo.importType("javax.ejb.Stateless")}
</#if>
public class ${declarationName}Home {

private static final ${pojo.importType("org.apache.commons.logging.Log")} log = ${pojo.importType("org.apache.commons.logging.LogFactory")}.getLog(${pojo.getDeclarationName()}Home.class);

<#if ejb3>
@${pojo.importType("javax.persistence.PersistenceContext")} private ${pojo.importType("javax.persistence.EntityManager")} entityManager;

public void persist(${declarationName} transientInstance) {
log.debug("persisting ${declarationName} instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
}
catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}

public void remove(${declarationName} persistentInstance) {
log.debug("removing ${declarationName} instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
}
catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}

public ${declarationName} merge(${declarationName} detachedInstance) {
log.debug("merging ${declarationName} instance");
try {
${declarationName} result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
}
catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

<#if clazz.identifierProperty?has_content>
public ${declarationName} findById( ${pojo.getJavaTypeName(clazz.identifierProperty, jdk5)} id) {
log.debug("getting ${declarationName} instance with id: " + id);
try {
${declarationName} instance = entityManager.find(${pojo.getDeclarationName()}.class, id);
log.debug("get successful");
return instance;
}
catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
</#if>
<#else>
private final ${pojo.importType("org.hibernate.SessionFactory")} sessionFactory;
/**
* Dependency injection constructor
*/
public ${declarationName}Home(final ${pojo.importType("org.hibernate.SessionFactory")} sessionFactory){
super();
this.sessionFactory = sessionFactory;
}

public void persist(${declarationName} transientInstance) {
log.debug("persisting ${declarationName} instance");
try {
sessionFactory.getCurrentSession().persist(transientInstance);
log.debug("persist successful");
}
catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}

public void attachDirty(${declarationName} instance) {
log.debug("attaching dirty ${declarationName} instance");
try {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
log.debug("attach successful");
}
catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void attachClean(${declarationName} instance) {
log.debug("attaching clean ${declarationName} instance");
try {
sessionFactory.getCurrentSession().lock(instance, ${pojo.importType("org.hibernate.LockMode")}.NONE);
log.debug("attach successful");
}
catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void delete(${declarationName} persistentInstance) {
log.debug("deleting ${declarationName} instance");
try {
sessionFactory.getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
}
catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}

public ${declarationName} merge(${declarationName} detachedInstance) {
log.debug("merging ${declarationName} instance");
try {
${declarationName} result = (${declarationName}) sessionFactory.getCurrentSession()
.merge(detachedInstance);
log.debug("merge successful");
return result;
}
catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

<#if clazz.identifierProperty?has_content>
public ${declarationName} findById( ${c2j.getJavaTypeName(clazz.identifierProperty, jdk5)} id) {
log.debug("getting ${declarationName} instance with id: " + id);
try {
${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession()
.get("${clazz.entityName}", id);
if (instance==null) {
log.debug("get successful, no instance found");
}
else {
log.debug("get successful, instance found");
}
return instance;
}
catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
</#if>

<#if clazz.hasNaturalId()>
public ${declarationName} findByNaturalId(${c2j.asNaturalIdParameterList(clazz)}) {
log.debug("getting ${declarationName} instance by natural id");
try {
${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession()
.createCriteria("${clazz.entityName}")
<#if jdk5>
.add( ${pojo.staticImport("org.hibernate.criterion.Restrictions", "naturalId")}()
<#else>
.add( ${pojo.importType("org.hibernate.criterion.Restrictions")}.naturalId()
</#if>
<#foreach property in pojo.getAllPropertiesIterator()>
<#if property.isNaturalIdentifier()>
.set("${property.name}", ${property.name})
</#if>
</#foreach>
)
.uniqueResult();
if (instance==null) {
log.debug("get successful, no instance found");
}
else {
log.debug("get successful, instance found");
}
return instance;
}
catch (RuntimeException re) {
log.error("query failed", re);
throw re;
}
}
</#if>
<#if jdk5>
public ${pojo.importType("java.util.List")}<${declarationName}> findByExample(${declarationName} instance) {
<#else>
public ${pojo.importType("java.util.List")} findByExample(${declarationName} instance) {
</#if>
log.debug("finding ${declarationName} instance by example");
try {
<#if jdk5>
${pojo.importType("java.util.List")}<${declarationName}> results = (List<${declarationName}>) sessionFactory.getCurrentSession()
<#else>
${pojo.importType("java.util.List")} results = sessionFactory.getCurrentSession()
</#if>
.createCriteria("${clazz.entityName}")
<#if jdk5>
.add( ${pojo.staticImport("org.hibernate.criterion.Example", "create")}(instance) )
<#else>
.add(${pojo.importType("org.hibernate.criterion.Example")}.create(instance))
</#if>
.list();
log.debug("find by example successful, result size: " + results.size());
return results;
}
catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
<#foreach queryName in cfg.namedQueries.keySet()>
<#if queryName.startsWith(clazz.entityName + ".")>
<#assign methname = c2j.unqualify(queryName)>
<#assign params = cfg.namedQueries.get(queryName).parameterTypes><#assign argList = c2j.asFinderArgumentList(params, pojo)>
<#if jdk5 && methname.startsWith("find")>
public ${pojo.importType("java.util.List")}<${declarationName}> ${methname}(${argList}) {
<#elseif methname.startsWith("count")>
public int ${methname}(${argList}) {
<#else>
public ${pojo.importType("java.util.List")} ${methname}(${argList}) {
</#if>
${pojo.importType("org.hibernate.Query")} query = sessionFactory.getCurrentSession()
.getNamedQuery("${queryName}");
<#foreach param in params.keySet()>
<#if param.equals("maxResults")>
query.setMaxResults(maxResults);
<#elseif param.equals("firstResult")>
query.setFirstResult(firstResult);
<#else>
query.setParameter("${param}", ${param});
</#if>
</#foreach>
<#if jdk5 && methname.startsWith("find")>
return (List<${declarationName}>) query.list();
<#elseif methname.startsWith("count")>
return ( (Integer) query.uniqueResult() ).intValue();
<#else>
return query.list();
</#if>
}
</#if>
</#foreach></#if>
}
</#assign>

${pojo.generateImports()}
${classbody}


Here are the classes and generated hbm files by hbm2java and jdbcconfiguration.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jan 15, 2008 10:00:09 AM by Hibernate Tools 3.2.0.CR1 -->
<hibernate-mapping>
<class name="persistance.Flights" table="flights" catalog="hibernate">
<id name="flightId" type="int">
<column name="flight_id" />
<generator class="assigned" />
</id>
<property name="name" type="string">
<column name="name" length="32" not-null="true" />
</property>
<property name="departureUtc" type="timestamp">
<column name="departure_utc" length="0" not-null="true" />
</property>
<property name="arrivalUtc" type="timestamp">
<column name="arrival_utc" length="0" not-null="true" />
</property>
<set name="reservationses" inverse="true">
<key>
<column name="flight_id_fk" not-null="true" />
</key>
<one-to-many class="persistance.Reservations" />
</set>
</class>
</hibernate-mapping>


Ant target:

<target name="generateall" depends="clean">
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="lib.class.path"/>
<hibernatetool destdir="${src.dir}" >
<jdbcconfiguration configurationfile="${src.dir}/hibernate.cfg.xml" packagename="persistance"/>
<hbm2hbmxml destdir="${build.gen-src.dir}/persistance"/>
<hbm2java jdk5="true"/>
<property key="ejb3" value="false"/>
<property key="jdk5" value="true"/>
<hbmtemplate templatepath="${src.dir}/template" template="my-dao-template.ftl"
filepattern="{package-name}/{class-name}Home.java"/>
</hibernatetool>
</target>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">*****</property>
</session-factory>
</hibernate-configuration>


Even though it is generating FilghtsHome.java why ant is throwing that error?

Here is the generated java file

package persistance;
// Generated Jan 15, 2008 10:00:11 AM by Hibernate Tools 3.2.0.CR1


import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import static org.hibernate.criterion.Example.create;

/**
* Home object for domain model class Flights.
* @see persistance.Flights
* @author Hibernate Tools
*/
public class FlightsHome {

private static final Log log = LogFactory.getLog(FlightsHome.class);

private final SessionFactory sessionFactory;
/**
* Dependency injection constructor
*/
public FlightsHome(final SessionFactory sessionFactory){
super();
this.sessionFactory = sessionFactory;
}

public void persist(Flights transientInstance) {
log.debug("persisting Flights instance");
try {
sessionFactory.getCurrentSession().persist(transientInstance);
log.debug("persist successful");
}
catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}

public void attachDirty(Flights instance) {
log.debug("attaching dirty Flights instance");
try {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
log.debug("attach successful");
}
catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void attachClean(Flights instance) {
log.debug("attaching clean Flights instance");
try {
sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
}
catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void delete(Flights persistentInstance) {
log.debug("deleting Flights instance");
try {
sessionFactory.getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
}
catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}

public Flights merge(Flights detachedInstance) {
log.debug("merging Flights instance");
try {
Flights result = (Flights) sessionFactory.getCurrentSession()
.merge(detachedInstance);
log.debug("merge successful");
return result;
}
catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public Flights findById( int id) {
log.debug("getting Flights instance with id: " + id);
try {
Flights instance = (Flights) sessionFactory.getCurrentSession()
.get("persistance.Flights", id);
if (instance==null) {
log.debug("get successful, no instance found");
}
else {
log.debug("get successful, instance found");
}
return instance;
}
catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}

public List<Flights> findByExample(Flights instance) {
log.debug("finding Flights instance by example");
try {
List<Flights> results = (List<Flights>) sessionFactory.getCurrentSession()
.createCriteria("persistance.Flights")
.add( create(instance) )
.list();
log.debug("find by example successful, result size: " + results.size());
return results;
}
catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
}


Thanks in advance....


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

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.