JBoss.orgCommunity Documentation
<hbm2java>
)<hbm2hbmxml>
)<hbm2cfgxml>
)<hbm2doc>
)<hbmtemplate>
)Maybe somebody will find it more preferable to use Ant for generation purposes. Thus, this chapter is intended to get you ready to start using Hibernate Tools via Ant tasks.
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.
There might be incompatibilities with respect to the Hibernate3.jar bundled with the tools and your own jar. Thus to avoid any confusion it is recommended to use the hibernate3.jar and 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. a Hibernate 3.1 project since the output generated 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
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 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 exporters |
Required |
templatepath |
A path to be used to look up user-edited templates |
Optional |
classpath |
A classpath to be used to resolve resources, such as mappings and usertypes |
Optional, but very often required |
property (and propertyset) |
Used to set properties to 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 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">
<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>, 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>
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.
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, plus lists the individual settings they have.
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"
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. "hibernate.cfg.xml" |
Optional |
propertyfile |
The name of a property file, e.g. "hibernate.properties" |
Optional |
entity-resolver |
Name of a class that implements org.xml.sax.EntityResolver. Used if the mapping files require custom entity resolver |
Optional |
namingstrategy |
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. |
Optional |
fileset |
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. |
This example shows an example where no
hibernate.cfg.xml
exists, and a
hibernate.properties
and fileset is used instead.
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>
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 jar files needed for using hibernate annotations in the classpath of the <taskdef>, i. e. hibernate-annotations.jar and hibernate-commons-annotations.jar.
The
<annotationconfiguration>
supports the same attributes as a
<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>
A <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 a JPA compliant manner.
The <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 a <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>
ejb3configuration was the name used in previous versions. It still works but will emit
a warning telling you to use jpaconfiguration
instead.
A
<jdbcconfiguration>
is used to perform reverse engineering of the database from a JDBC connection.
This configuration works by reading the connection properties either from hibernate.cfg.xml or hibernate.properties with a fileset.
The
<jdbcconfiguration>
has the same attributes as a
<configuration>
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. "hibernate.properties" |
Optional |
reversestrategy |
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. |
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 <version> or <timestamp>. |
Default: true |
Here is an example of using
<jdbcconfiguration>
to generate Hibernate xml mappings via
<hbm2hbmxml>. The connection settings here
is 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>
Exporters are the parts that 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 for
userdefined exporters, that 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 placed on 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" 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). |
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 |
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 codegenerator. 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 javax.persistence and org.hibernate.annotations |
False |
<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.
Not every possible mapping transformation is possible/implemented (contributions welcome) so some hand editing might be necessary.
<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. 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 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 cfg.xml will have <mapping class=".."/>, opposed to <mapping resource="..."/> for each mapping. |
False |
<hbm2doc> generates html documentation a'la javadoc for the database schema et.al.
<hbm2doc/>
<query> is used to execute a HQL query statements and optionally sends 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 and the query is executed via the list() method. In the future more options might become available, like performing executeUpdate(), use named queries and etc.
The 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.
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>
Generic exporter that can be controlled by a user provides a 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 us much better exception and error handling.
The following is an example of reverse engineering via <jdbcconfiguration> and usage of a custom Exporter via the <hbmtemplate> .
<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>
Read more about Velocity and Freemarker to find out why using the last is better or refer to Max Andersen discussion on the topic in "A story about FreeMarker and Velocity".
Exporters can be controlled by user properties. The user properties are specified via
<property>
or
<propertyset>
and each exporter will have access to them directly in the templates and via
Exporter.setProperties().
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>
that is used for grouping a set of properties. More about the functionality of
<propertyset>
is explained in detail in the Ant
manual.
If the templates need to access some user class it becomes 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 useful to delegate logic and code generation to java
code instead of placing such logic in the templates.
Here is an example that uses <hbmtemplate> together with <property> which will be available to the templates/exporter.
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>