JBoss.orgCommunity Documentation
This chapter demonstrates how to use Hibernate Tools via Ant tasks.
The hibernate-tools.jar
file, available from tools.hibernate.org, contains the core code for Hibernate Tools™. It is used as the basis for both the Ant tasks described in this document and the Eclipse plugins available as part of JBoss Developer Studio. The hibernate-tools.jar
file 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.
There may be incompatibilities with respect to the hibernate3.jar
bundled with the tools and your own JAR. To avoid any confusion it is recommended that you use the hibernate3.jar
and hibernate-annotations.jar
files bundled with the tools when you want to use the Ant tasks. Do not worry about using the JAR's from a later version of Hibernate (e.g. Hibernate 3.2) with a project using an earlier version of Hibernate (e.g. a Hibernate 3.1) since the generated output will work with previous Hibernate 3 versions.
To use the Ant tasks you need to have the hibernatetool
task defined. That is done in your build.xml
file by inserting the following XML (assuming the JARs are located 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 an 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.
When using the hibernatetool
task you have to specify one or more of the following:
<hibernatetool destdir="defaultDestinationDirectory" templatepath="defaultTemplatePath" > <classpath ...> <property key="propertyName" value="value"/> <propertyset ...> (<configuration ...>|<annotationconfiguration ...>| <jpaconfiguration ...>|<jdbcconfiguration ...>) (<hbm2java>,<hbm2cfgxml>,<hbmtemplate>,...) </hibernatetool>
Table 5.1. Hibernatetool attributes
Attribute name | Definition | Attribute use |
---|---|---|
destdir |
Destination directory for files generated with the exporters |
Required |
templatepath |
A path used for looking up user-edited templates |
Optional |
classpath |
A classpath to be used to resolve resources, such as mappings and user types |
Optional, but very often required |
property (and propertyset) |
Used to set properties that control the exporters. Mostly relevant for providing custom properties to user defined templates |
Optional |
configuration (annotationconfiguration, jpaconfiguration, jdbcconfiguration) |
One of four different ways of configuring the Hibernate Meta Model must be specified | |
hbm2java (hbm2cfgxml, hbmtemplate, etc.) |
One or more of the exporters must be specified |
The following example shows the most basic setup for generating POJOs via <hbm2java>
from a normal hibernate.cfg.xml
file. The output will be placed in the ${build.dir}/generated
directory.
<hibernatetool destdir="${build.dir}/generated"> <classpath> <path location="${build.dir}/classes"/> </classpath> <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>
, generating some DAO code via <hbm2dao>
, and finally running some custom code generation via <hbmtemplate>
. This is again from a normal hibernate.cfg.xml
file, and the output is still placed in the ${build.dir}/generated
directory.
The example also shows how a classpath is specified, which is useful when you have custom user types or some mappings that are required 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>
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>
) used when reverse engineering.
Each can be used to build a Hibernate Configuration object, from which a set of exporters can be run in order to generate various output formats.
Output can be anything, e.g. specific files, statements execution against a database, error reporting or anything else that can be done in Java code.
The following sections describe what the various configurations can do, as well as listing their individual settings.
A <configuration>
tag is used to define a standard Hibernate configuration. A standard Hibernate configuration reads the mappings from a cfg.xml
file and/or a fileset.
<configuration configurationfile="hibernate.cfg.xml" propertyfile="hibernate.properties" entityresolver="EntityResolver classname" namingstrategy="NamingStrategy classname" > <fileset...> </configuration>
Table 5.2. Configuration attributes
Attribute name | Definition | Attribute use |
---|---|---|
configurationfile |
The name of a Hibernate configuration file, e.g. |
Optional |
propertyfile |
The name of a property file, e.g. |
Optional |
entity-resolver |
Name of a class that implements |
Optional |
namingstrategy |
Name of a class that implements |
Optional |
fileset |
A standard Ant fileset. Used to include hibernate mapping files. Remember that if mappings are already specified in the |
This example shows an example where no hibernate.cfg.xml
file exists, and a hibernate.properties
file and fileset is used instead.
Hibernate will still read any global hibernate.properties
files 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>
An <annotationconfiguration>
tag is used when you want to read the metamodel from EJB3 or Hibernate Annotations based POJO's.
To use an <annotationconfiguration>
tag remember to place the JAR files required to use Hibernate annotations in the classpath of the <taskdef>
, i.e. hibernate-annotations.jar
and hibernate-commons-annotations.jar
.
The <annotationconfiguration>
tag supports the same attributes as the <configuration>
tag, with the exception being that the configurationfile
attribute is now required as that is where an AnnotationConfiguration gets the list of classes and packages it should load.
Thus the minimal usage is:
<hibernatetool destdir="${build.dir}/generated"> <annotationconfiguration configurationfile="hibernate.cfg.xml"/> <!-- list exporters here --> </hibernatetool>
A <jpaconfiguration>
tag is used when you want to read the metamodel from JPA or Hibernate Annotation where you want to use the auto-scan configuration as defined in the JPA specification (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
file packaged in a JPA compliant manner.
The <jpaconfiguration>
tag will try and auto-configure it self based on the available classpath, e.g. look for the META-INF/persistence.xml
file.
The persistenceunit
attribute can be used to select a specific persistence unit. If no persistenceunit
attribute is specified it will automatically search for one, and if a unique one is found, use it. However, having multiple persistence units will result in an error.
To use a <jpaconfiguration>
tag you will need to specify some additional JARs from the Hibernate EntityManager in the <taskdef>
section of the hibernatetool. The following demonstrates 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>
ejb3configuration
was the name used in previous versions. It still works but will display a warning telling you to use jpaconfiguration
instead.
A <jdbcconfiguration>
tag is used to perform reverse engineering of a database from a JDBC connection.
This configuration works by reading the connection properties either from a hibernate.cfg.xml
file or a hibernate.properties
file with a fileset.
The <jdbcconfiguration>
tag has the same attributes as a <configuration>
tag, plus the following additional attributes:
<jdbcconfiguration ... packagename="package.name" revengfile="hibernate.reveng.xml" reversestrategy="ReverseEngineeringStrategy classname" detectmanytomany="true|false" detectoptmisticlock="true|false" > ... </jdbcconfiguration>
Table 5.3. Jdbcconfiguration attributes
Attribute name | Definition | Attribute use |
---|---|---|
packagename |
The default package name to use when mappings for classes are created |
Optional |
revengfile |
The name of a property file, e.g. |
Optional |
reversestrategy |
Name of a class that implements |
Optional |
detectManytoMany |
If true, 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 exactly two foreign-keys pointing to other entity tables and has no other columns. |
Default: true |
detectOptimisticLock |
If true, columns named VERSION or TIMESTAMP with appropriate types will be mapped with the appropriate optimistic locking corresponding to
|
Default: true |
Here is an example using a <jdbcconfiguration>
tag to generate Hibernate XML mappings via <hbm2hbmxml>
. The connection settings used here are read from a hibernate.properties
file, but they could also have been defined in a hibernate.cfg.xml
file.
<hibernatetool> <jdbcconfiguration propertyfile="etc/hibernate.properties" /> <hbm2hbmxml destdir="${build.dir}/src" /> </hibernatetool>
Exporters do 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 to implement user defined exporters, which is done through the <hbmtemplate>
exporter.
<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 defined in the configuration element.
<hbm2ddl export="true|false" update="true|false" drop="true|false" create="true|false" outputfilename="filename.ddl" delimiter=";" format="true|false" haltonerror="true|false" >
Table 5.4. Hbm2ddl exporter attributes
Attribute name | Definition | Attribute use |
---|---|---|
export |
Executes the generated statements against the database |
Default: true |
update |
Try and create an update script representing the "delta" that is, between what is in the database and what the mappings specify. Ignores create and update attributes. (Do *not* use against production databases, as there are no guarantees that the proper delta can be generated, nor that the underlying database can actually execute the required operations). |
Default: false |
drop |
Output will contain drop statements for the tables, indices and constraints |
Default: false |
create |
Output will contain create statements for the tables, indices and constraints |
Default: true |
outputfilename |
If specified the statements will be dumped to this file |
Optional |
delimiter |
If specified the statements will be dumped to this file |
Default: ";" |
format |
Apply basic formatting to the statements |
Default: false |
haltonerror |
Halt build process if an error occurs |
Default: false |
Below is a 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>
<hbm2java>
is a Java code generator. Options for controlling whether JDK 5 syntax can be used and whether the POJO should be annotated with EJB3/Hibernate Annotations.
<hbm2java jdk5="true|false" ejb3="true|false" >
Table 5.5. Hbm2java exporter attributes
Attribute name | Definition | Default value |
---|---|---|
jdk |
Code will contain JDK 5 constructs such as generics and static imports |
False |
ejb3 |
Code will contain EJB 3 features, e.g. using annotations from |
False |
<hbm2hbmxml>
generates a set of .hbm
files. It is 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 a hbm.xml
file.
Not every possible mapping transformation is possible/implemented (contributions welcome) so some hand editing might be required.
<hbm2hbmxml/>
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>
.
Not all conversions are implemented (contributions welcome), so some hand editing might be necessary.
<hibernatetool destdir="${build.dir}/generated"> <annotationconfiguration configurationfile="hibernate.cfg.xml"/> <hbm2hbmxml/> </hibernatetool>
<hbm2cfgxml>
generates a hibernate.cfg.xml
file. It is intended to be used together with a <jdbcconfiguration>
when performing reverse engineering, but it can be used with any kind of configuration. The <hbm2cfgxml>
will contain the properties that are used and adds mapping entries for each mapped class.
<hbm2cfgxml ejb3="true|false" />
Table 5.6. Hbm2cfgxml exporter attribute
Attribute name | Definition | Default value |
---|---|---|
ejb3 |
The generated |
False |
<hbm2doc>
generates HTML documentation similar to Javadoc for the database schema et.al.
<hbm2doc/>
<query>
is used to execute HQL query statements and optionally redirects the output to a file. It 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, which are executed via the list()
method. In the future more options might become available, like executing executeUpdate()
, use named queries and etc.
The simplest usage of <query>
will execute the query without dumping to a file. This can be used to verify that queries can be performed successfully.
<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 the queryresult.txt
file.
Currently the dump is performed by calling the toString()
function 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>
Below is an example of a 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" />
Previous versions of the tools used Velocity™. We are now using Freemarker™, which provides much better exception and error handling.
The following is an example of reverse engineering via a <jdbcconfiguration>
tag and the use of a custom Exporter via the <hbmtemplate>
tag.
<hibernatetool destdir="${destdir}"> <jdbcconfiguration configurationfile="hibernate.cfg.xml" packagename="my.model"/> <!-- setup properties --> <property key="appname" value="Registration"/> <property key="shortname" value="crud"/> <hbmtemplate exporterclass="my.own.Exporter" filepattern="."/> </hibernatetool>
You can read more about Velocity and Freemarker to find out why using the latter is better or refer to Max Andersens discussion on the topic in "A story about FreeMarker and Velocity".
Exporters can be controlled by user properties. These user properties are specified via a <property>
or <propertyset>
tag, and each exporter will have access to them directly in the templates and via Exporter.setProperties()
.
The <property>
tag allows you bind a string value to a key. The value will be available in the templates via the $<key>
tag. The following example will assign the string value "true"
to the variable $descriptors
.
<property key="descriptors" value="true"/>
Usually using the <property>
tag is enough when specifying the properties required by the exporters. Still, the Ant tools supports the notion of a <propertyset>
which is used for grouping a set of properties. More about the functionality of <propertyset>
is can be found in the Ant manual.
It is possible for the templates to access user classes by specifying a "toolclass"
in the properties.
<property key="hibernatetool.sometool.toolclass" value="x.y.z.NameOfToolClass"/>
Placing the above <property>
tag in the <hibernatetool>
tag or inside any exporter will automatically create an instance of x.y.z.NameOfToolClass
which will be available in the templates as $sometool
. This is useful to delegate logic and code generation to Java code instead of placing such logic in the templates.
Here is an example that uses the <hbmtemplate>
tag together with the <property>
tag, which will be available to the templates and exporter.
This example actually simulates what the <hbm2java>
tag 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>