Chapter 4. Ant Tools

4.1. Introduction

The hibernate-tools.jar contains the core for the Hibernate Tools. It is used as the basis for both the Ant tasks described in this document and the eclipse plugins both available from tools.hibernate.org The hibernate-tools.jar is located in your eclipse plugins directory at

/plugins/org.hibernate.eclipse.x.x.x/lib/tools/hibernate-tools.jar

. This jar is 100% independent from the eclipse platform and can thus be used independently of eclipse.

Note: until Hibernate 3.2 and related libraries are finally released there might be incompabilities with respect to the tools. Thus to avoid any confusion it is recommended to use the hibernate3.jar & hibernate-annotations.jar bundled with the tools when you want to use the Ant tasks. Do not worry about using e.g. Hibernate 3.2 jar's with e.g. an Hibernate 3.1 project since the output generated will work with previous Hibernate 3 versions.

4.2. The <hibernatetool> ant Task

To use the ant tasks you need to have the hibernatetool task defined. That is done in your build.xml by inserting the following xml (assuming the jars are in the lib directory):

<path id="toolslib">
 <path location="lib/hibernate-tools.jar" />
 <path location="lib/hibernate3.jar" />
 <path location="lib/freemarker.jar" />
 <path location="${jdbc.driver.jar}" />
</path>
   
<taskdef name="hibernatetool" 
         classname="org.hibernate.tool.ant.HibernateToolTask" 
         classpathref="toolslib" />

this <taskdef> defines a Ant task called <hibernatetool> which now can be used anywhere in your ant build.xml files. It is important to include all the hibernate tools dependencies as well as the jdbc driver.

Notice that to use the annotation based Configuration you must get a release from http://annotations.hibernate.org.

When using the <hibernatetool> task you have to specify one or more of the following:

<hibernatetool
  destdir="defaultDestinationDirectory"               (1)
  templatepath="defaultTemplatePath"                  (2)
>                                                     (3)
  <classpath ...>
  <property key="propertyName" value="value"/>
  <propertyset ...>                                   (4)
  (<configuration ...>|<annotationconfiguration ...>| (5)
   <jpaconfiguration ...>|<jdbcconfiguration ...>)
  (<hbm2java>,<hbm2cfgxml>,<hbmtemplate>,...*)        (6)
</hibernatetool>
(1)

destdir (required): destination directory for files generated with exporters.

(2)

templatepath (optional): A path to be used to look up user-edited templates.

(3)

classpath (optional): A classpath to be used to resolve resources, such as mappings and usertypes. Optional, but very often required.

(4)

property and propertyset (optional): Used to set properties to control the exporters. Mostly relevant for providing custom properties to user defined templates.

(5)

One of 4 different ways of configuring the Hibernate Meta Model must be specified.

(6)

One or more of the exporters must be specified

4.2.1. Basic examples

The following example shows the most basic setup for generating pojo's via hbm2java from a normal hibernate.cfg.xml. The output will be put in the ${build.dir}/generated directory.

<hibernatetool destdir="${build.dir}/generated">
 <configuration configurationfile="hibernate.cfg.xml"/>
 <hbm2java/>
</hibernatetool>

The following example is similar, but now we are performing multiple exports from the same configuration. We are exporting the schema via hbm2dll, generates some DAO code via <hbm2dao> and finally runs a custom code generation via <hbmtemplate>. This is again from a normal hibernate.cfg.xml and the output is still put in the ${build.dir}/generated directory. Furthermore the example also shows where a classpath is specified when you e.g. have custom usertypes or some mappings that is needed to be looked up as a classpath resource.

<hibernatetool destdir="${build.dir}/generated">
 <classpath>
  <path location="${build.dir}/classes"/>
 </classpath>

 <configuration configurationfile="hibernate.cfg.xml"/>
 <hbm2ddl/>
 <hbm2dao/>
 <hbmtemplate
  filepattern="{package-name}/I{class-name}Constants.java"
  templatepath="${etc.dir}/customtemplates"
  template="myconstants.vm"  
 />
</hibernatetool>

4.3. Hibernate Configurations

hibernatetool supports four different Hibernate configurations: A standard Hibernate configuration (<configuration>), Annotation based configuration (<annotationconfiguration>), JPA persistence based configuration (<jpaconfiguration>) and a JDBC based configuration (<jdbcconfiguration>) for use when reverse engineering.

Each have in common that they are able to build up a Hibernate Configuration object from which a set of exporters can be run to generate various output. Note: output can be anything, e.g. specific files, statments execution against a database, error reporting or anything else that can be done in java code.

The following section decribes what the the various configuration can do, plus list the individual settings they have.

4.3.1. Standard Hibernate Configuration (<configuration>)

A <configuration> is used to define a standard Hibernate configuration. A standard Hibernate configuration reads the mappings from a cfg.xml and/or a fileset.

<configuration
  configurationfile="hibernate.cfg.xml"               (1)
  propertyfile="hibernate.properties"                 (2)
  entityresolver="EntityResolver classname"           (3)
  namingstrategy="NamingStrategy classname"           (4)
>
  <fileset...>                                        (5)
  
</configuration>
(1)

configurationfile (optional): The name of a Hibernate configuration file, e.g. "hibernate.cfg.xml"

(2)

propertyfile (optional): The name of a property file, e.g. "hibernate.properties"

(3)

entity-resolver (optional): name of a class that implements org.xml.sax.EntityResolver. Used if the mapping files require custom entity resolver.

(4)

namingstrategy (optional): name of a class that implements org.hibernate.cfg.NamingStrategy. Used for setting up the naming strategy in Hibernate which controls the automatic naming of tables and columns.

(5)

A standard Ant fileset. Used to include hibernate mapping files.Remember that if mappings are already specified in the hibernate.cfg.xml then it should not be included via the fileset as it will result in duplicate import exceptions.

4.3.1.1. Example

This example shows an example where no hibernate.cfg.xml exists, and a hibernate.properties + fileset is used instead. Note, that Hibernate will still read any global /hibernate.properties available in the classpath, but the specified properties file here will override those values for any non-global property.

<hibernatetool destdir="${build.dir}/generated">
 <configuration propertyfile="{etc.dir}/hibernate.properties">
   <fileset dir="${src.dir}">
   <include name="**/*.hbm.xml"/>
   <exclude name="**/*Test.hbm.xml"/>
  </fileset>
 </configuration>

 <!-- list exporters here -->

</hibernatetool>

4.3.2. Annotation based Configuration (<annotationconfiguration>)

An <annotationconfiguration> is used when you want to read the metamodel from EJB3/Hibernate Annotations based POJO's. To use it remember to put the jars file needed for using hibernate annotations in the classpath of the <taskdef>.

The <annotationconfiguration> supports the same attributes as an <configuration> except that the configurationfile attribute is now required as that is from where an AnnotationConfiguration gets the list of classes/packages it should load.

Thus the minimal usage is:

<hibernatetool destdir="${build.dir}/generated">
 <annotationconfiguration
  configurationfile="hibernate.cfg.xml"/>

 <!-- list exporters here -->

</hibernatetool>

4.3.3. JPA based configuration (<jpaconfiguration>)

An <jpaconfiguration> is used when you want to read the metamodel from JPA/Hibernate Annotation where you want to use the auto-scan configuration as defined in the JPA spec (part of EJB3). In other words, when you do not have a hibernate.cfg.xml, but instead have a setup where you use a persistence.xml packaged in an JPA compliant manner.

<jpaconfiguration> will simply just try and auto-configure it self based on the available classpath, e.g. look for META-INF/persistence.xml.

The persistenceunit attribute can be used to select a specific persistence unit. If no persistenceunit is specified it will automatically search for one and if a unique one is found use it, but if multiple persistence units are available it will error.

To use an <jpaconfiguration> you will need to specify some additional jars from Hibernate EntityManager in the <taskdef> of the hibernatetool. The following shows a full setup:

<path id="ejb3toolslib">
 <path refid="jpatoolslib"/> <!-- ref to previously defined toolslib -->
 <path location="lib/hibernate-annotations.jar" />
 <path location="lib/ejb3-persistence.jar" />
 <path location="lib/hibernate-entitymanager.jar" />
 <path location="lib/jboss-archive-browsing.jar" />
 <path location="lib/javaassist.jar" /> 
</path>
   
<taskdef name="hibernatetool" 
         classname="org.hibernate.tool.ant.HibernateToolTask" 
         classpathref="jpatoolslib" />

<hibernatetool destdir="${build.dir}">
 <jpaconfiguration persistenceunit="caveatemptor"/>
 <classpath>
  <!-- it is in this classpath you put your classes dir,
   and/or jpa persistence compliant jar -->
  <path location="${build.dir}/jpa/classes" />
 </classpath>

 <!-- list exporters here -->

</hibernatetool>

Note: ejb3configuration were the name used in previous versions. It still works but will emit a warning telling you to use jpaconfiguration instead.

4.3.4. JDBC Configuration for reverse engineering (<jdbcconfiguration>)

A <jdbcconfiguration> is used to perform reverse engineering of the database from a JDBC connection.

This configuration works by reading the connection properties from

The <jdbcconfiguration> has the same attributes as a <configuration> plus the following additional attributes:

<jdbcconfiguration
  ...
  packagename="package.name"                            (1)
  revengfile="hibernate.reveng.xml"                     (2)
  reversestrategy="ReverseEngineeringStrategy classname"(3)
  detectmanytomany="true|false"                         (4)
  detectoptmisticlock="true|false"                      (5)
>
  ...
</jdbcconfiguration>
(1)

packagename (optional): The default package name to use when mappings for classes is created

(2)

revengfile (optional): name of reveng.xml that allows you to control various aspects of the reverse engineering.

(3)

reversestrategy (optional): name of a class that implements org.hibernate.cfg.reveng.ReverseEngineeringStrategy. Used for setting up the strategy the tools will use to control the reverse engineering, e.g. naming of properties, which tables to include/exclude etc. Using a class instead of (or as addition to) a reveng.xml file gives you full programmatic control of the reverse engineering.

(4)

detectManytoMany (default:true): If true (the default) tables which are pure many-to-many link tables will be mapped as such. A pure many-to-many table is one which primary-key contains has exactly two foreign-keys pointing to other entity tables and has no other columns.

(5)

detectOptimisticLock (efault:true): If true columns named VERSION or TIMESTAMP with appropriate types will be mapped with the apropriate optimistic locking corresponding to <version> or <timestamp>

4.3.4.1. Example

Here is an example of using <jdbcconfiguration> to generate Hibernate xml mappings via <hbm2hbmxml>. The connection settings is here read from a hibernate.properties file but could just as well have been read from a hibernate.cfg.xml.

<hibernatetool>
 <jdbcconfiguration propertyfile="etc/hibernate.properties" />
 <hbm2hbmxml destdir="${build.dir}/src" /> 
</hibernatetool>

4.4. Exporters

Exporters is the parts that does the actual job of converting the hibernate metamodel into various artifacts, mainly code. The following section describes the current supported set of exporters in the Hibernate Tool distribution. It is also possible for userdefined exporters, that is done through the <hbmtemplate> exporter.

4.4.1. Database schema exporter (<hbm2ddl>)

<hbm2ddl> lets you run schemaexport and schemaupdate which generates the appropriate SQL DDL and allow you to store the result in a file or export it directly to the database. Remember that if a custom naming strategy is needed it is placed on the configuration element.

<hbm2ddl
 export="true|false"                                  (1)
 update="true|false"                                  (2)
 drop="true|false"                                    (3)
 create="true|false"                                  (4)
 outputfilename="filename.ddl"                        (5)
 delimiter=";"                                        (6)
 format="true|false"                                  (7)(8)
 haltonerror="true|false"
>
(1)

export (default: true): Execute the generated statements against the database

(2)

update(default: false): Try and create an update script representing the "delta" between what is in the database and what the mappings specify. Ignores create/update attributes. (Do *not* use against production databases, no guarantees at all that the proper delta can be generated nor that the underlying database can actually execute the needed operations)

(3)

drop (default: false): Output will contain drop statements for the tables, indices & constraints

(4)

create (default: true): Output will contain create statements for the tables, indices & constraints

(5)

outputfilename (Optional): If specified the statements will be dumped to this file.

(6)

delimiter (default: ";"): What delimter to use to separate statements

(7)

format (default: false): Apply basic formatting to the statements.

(8)

haltonerror (default: false): Halt build process if an error occurs.

4.4.1.1. Example

Basic example of using <hbm2ddl>, which does not export to the database but simply dumps the sql to a file named sql.ddl.

<hibernatetool destdir="${build.dir}/generated">
 <configuration configurationfile="hibernate.cfg.xml"/>
 <hbm2ddl export="false" outputfilename="sql.ddl"/>
</hibernatetool>

4.4.2. POJO java code exporter (<hbm2java>)

<hbm2java> is a java codegenerator. Options for controlling wether JDK 5 syntax can be used and wether the POJO should be annotated with EJB3/Hibernate Annotations.

<hbm2java
 jdk5="true|false"                                    (1)
 ejb3="true|false"                                    (2)
>
(1)

jdk (default: false): Code will contain JDK 5 constructs such as generics and static imports

(2)

ejb3 (default: false): Code will contain EJB 3 features, e.g. using annotations from javax.persistence and org.hibernate.annotations

4.4.2.1. Example

Basic example of using <hbm2java> to generate POJO's that utilize jdk5 constructs.

<hibernatetool destdir="${build.dir}/generated">
 <configuration configurationfile="hibernate.cfg.xml"/>
 <hbm2java jdk5="true"/>
</hibernatetool>

4.4.3. Hibernate Mapping files exporter (<hbm2hbmxml>)

<hbm2hbmxml> generates a set of .hbm files. Intended to be used together with a <jdbcconfiguration> when performing reverse engineering, but can be used with any kind of configuration. e.g. to convert from annotation based pojo's to hbm.xml. Note that not every possible mapping transformation is possible/implemented (contributions welcome) so some hand editing might be necessary.

<hbm2hbmxml/>

4.4.3.1. Example

Basic usage of <hbm2hbmxml>

<hibernatetool destdir="${build.dir}/generated">
 <configuration configurationfile="hibernate.cfg.xml"/>
 <hbm2hbmxml/>
</hibernatetool>

<hbm2hbmxml> is normally used with a <jdbcconfiguration> like in the above example, but any other configuration can also be used to convert between the different ways of performing mappings. Here is an example of that, using an <annotationconfiguration>. Note: not all conversions is implemented (contributions welcome), so some hand editing might be necessary.

<hibernatetool destdir="${build.dir}/generated">
 <annotationconfiguration configurationfile="hibernate.cfg.xml"/>
 <hbm2hbmxml/>
</hibernatetool>

4.4.4. Hibernate Configuration file exporter (<hbm2cfgxml>)

<hbm2cfgxml> generates a hibernate.cfg.xml. Intended to be used together with a <jdbcconfiguration> when performing reverse engineering, but can be used with any kind of configuration. The <hbm2cfgxml> will contain the properties used and adds mapping entries for each mapped class.

<hbm2cfgxml
  ejb3="true|false"                                   (1)
/>
(1)

ejb3 (default: false): the generated cfg.xml will have <mapping class=".."/>, opposed to <mapping resource="..."/> for each mapping.

4.4.5. Documentation exporter (<hbm2doc>)

<hbm2doc> generates html documentation a'la javadoc for the database schema et.al.

<hbm2doc/>

4.4.6. Query exporter (<query>)

<query> is used to execute a HQL query statements and optionally send the output to a file. Can be used for verifying the mappings and for basic data extraction.

<query
 destfile="filename">
 <hql>[a HQL query string]</hql>
</query>

Currently one session is opened and used for all queries and the query is executed via the list() method. In the future more options might become available, like performing executeUpdate(), use named queries etc.

4.4.6.1. Examples

Simplest usage of <query> will just execute the query without dumping to a file. This can be used to verify that queries can actually be performed.

<hibernatetool>
 <configuration configurationfile="hibernate.cfg.xml"/>
 <query>from java.lang.Object</query>
</hibernatetool>

Multiple queries can be executed by nested <hql> elements. In this example we also let the output be dumped to queryresult.txt. Note that currently the dump is simply a call to toString on each element.

<hibernatetool>
 <configuration configurationfile="hibernate.cfg.xml"/>
 <query destfile="queryresult.txt">
   <hql>select c.name from Customer c where c.age > 42</hql>
   <hql>from Cat</hql>
</hibernatetool>

4.4.7. Generic Hibernate metamodel exporter (<hbmtemplate>)

Generic exporter that can be controlled by a user provided template or class.

<hbmtemplate
 filepattern="{package-name}/{class-name}.ftl"
 template="somename.ftl"
 exporterclass="Exporter classname"
/>

NOTICE: Previous versions of the tools used Velocity. We are now using Freemarker which provides us much better exception and error handling.

4.4.7.1. Seam Exporter via <hbmtemplate>

The following is an example of reverse engineering via <jdbcconfiguration> and use the SeamExporter via the <hbmtemplate> to generate a Seam application skeleton.

 <hibernatetool destdir="${destdir}">
  <jdbcconfiguration 
     configurationfile="hibernate.cfg.xml" 
     packagename="x.y.z.seam.crud"/>   
  
  <!-- setup properties -->  
  <property key="seam_appname" value="Registration"/>
  <property key="seam_shortname" value="crud"/>
    
  <hbmtemplate 
     exporterclass="org.hibernate.tool.hbm2x.seam.SeamExporter" 
     filepattern="."/>
        
</hibernatetool>

4.5. Using properties to configure Exporters

Exporters can be controlled by user properties. The user properties is specificed via <property> or <propertyset> and each exporter will have access to them directly in the templates and via Exporter.setProperties().

4.5.1. <property> and <propertyset>

The <property> allows you bind a string value to a key. The value will be available in the templates via $<key>. The following example will assign the string value "true" to the variable $descriptors

<property key="descriptors" value="true"/>

Most times using <property> is enough for specifying the properties needed for the exporters. Still the ant tools supports the notion of <propertyset>. The functionallity of <propertyset> is explained in detail in the Ant task manual.

4.5.2. Getting access to user specific classes

If the templates need to access some user class it is possible by specifying a "toolclass" in the properties.

<property key="hibernatetool.sometool.toolclass" value="x.y.z.NameOfToolClass"/>

Placing the above <property> tag in <hibernatetool> or inside any exporter will automatically create an instance of x.y.z.NameOfToolClass and it will be available in the templates as $sometool. This is usefull to delegate logic and code generation to java code instead of placing such logic in the templates.

4.5.2.1. Example

Here is an example that uses <hbmtemplate> together with <property> which will be available to the templates/exporter. Note: This example actually simulates what <hbm2java> actually does.

<hibernatetool destdir="${build.dir}/generated">
<configuration 
   configurationfile="etc/hibernate.cfg.xml"/>
 <hbmtemplate 
   templateprefix="pojo/" 
   template="pojo/Pojo.ftl" 
   filepattern="{package-name}/{class-name}.java">
  <property key="jdk5" value="true" />
  <property key="ejb3" value="true" />
 </hbmtemplate>
</hibernatetool>