<hbm2java>)<hbm2hbmxml>)<hbm2cfgxml>)<hbm2doc>)<hbmtemplate>)Hibernate Tools is a toolset for Hibernate 3 and related projects. The tools provide Ant tasks and Eclipse plugins for performing reverse engineering, code generation, visualization and interaction with Hibernate.
Hibernate Tools can be used "standalone" via Ant 1.6.x or fully integrated into an Eclipse 3.3.x + WTP 2.x based IDE, such as JBoss Tools or a default Eclipse 3.3.x + WTP 2.x installation. The following describes the install steps in these environments.
JBoss Tools 2.x includes Hibernate Tools and thus nothing is required besides downloading and installing JBoss Tools. If you need to update to a newer version of the Hibernate Tools just follow the instructions in the Eclipse IDE section.
To install into any Eclipse 3.3.x based Eclipse IDE you can either download the Hibernate Tools distribution from the Hibernate website or use the JBoss Tools Update Site (see also http://tools.hibernate.org for links to the update site).
If you download the Hibernate Tools distribution you need to place the /plugins and /feature directory into your eclipse directory or eclipse extensions directory. Sometimes Eclipse does not automatically detect new plugins and thus the tools will not be activated. To ensure eclipse sees these changes just clean up the cached plugin information by running eclipse with the -clean option, e.g. eclipse -clean. Using the updatesite does not require any additional steps.
If you need more basic instructions on installing plugins and general usage of eclipse then check out https://eclipse-tutorial.dev.java.net/ and especially https://eclipse-tutorial.dev.java.net/visual-tutorials/updatemanager.html which covers using the update manager.
The Hibernate Tools plugins currently use WTP 2.x which at this time is the latest stable release from the Eclipse Webtools project.
Because the WTP project not always have had proper versioning of their plugins there might exist WTP plugins in your existing eclipse directory from other Eclipse based projects that are from an earlier WTP release but has either the same version number or higher. It is thus recommended that if you have issues with WTP provided features to try and install the plugins on a clean install of eclipse to ensure there are no version collisions.
To use the tools via Ant you need the hibernate-tools.jar and associated libraries. The libraries are included in the distribution from the Hibernate website and the Eclipse updatesite. The libraries are located in the eclipse plugins directory at /plugins/org.hibernate.eclipse.x.x.x/lib/tools/. These libraries are 100% independent from the eclipse platform. How to use these via ant tasks are described in the Ant Tools chapter.
The code generation mechanism in the Hibernate Tools consists of a few core concepts. This section explains their overall structure which are the same for the Ant and Eclipse tools.
The meta model is the model used by Hibernate Core to perform its object relational
mapping. The model includes information about tables, columns, classes, properties,
components, values, collections etc. The API is in org.hibernate.mapping
and its main entry point is the Configuration class, the same class that is
used to build a session factory.
The model represented by the Configuration class can be build in many
ways. The following list the currently supported ones in Hibernate Tools.
A Core configuration uses Hibernate Core and supports reading
hbm.xml
files, requires a
hibernate.cfg.xml
. Named core in Eclipse and
<configuration>
in ant.
An Annotation configuration uses Hibernate Annotations and supports
hbm.xml
and annotated classes, requires a
hibernate.cfg.xml
. Named annotations in Eclipse and
<annotationconfiguration>
in ant.
A JPA configuration uses a Hibernate EntityManager and supports
hbm.xml
and annotated classes requires that the project has a
META-INF/persistence.xml
in its classpath. Named JPA in Eclipse and
<jpaconfiguration>
in ant.
A JDBC configuration uses Hibernate Tools reverse engineering
and reads its mappings via JDBC metadata + additional reverse engineering files
(reveng.xml). Automatically used in Eclipse when doing reverse engineering from JDBC and
named
<jdbcconfiguration>
in ant.
In most projects you will normally use only one of the Core, Annotation or JPA configuration and possibly the JDBC configuration if you are using the reverse engineering facilities of Hibernate Tools.
No matter which Hibernate Configuration type you are using Hibernate Tools supports them.
The following drawing illustrates the core concepts:
The code generation is done based on the Configuration model no matter which type of configuration have been used to create the meta model, and thus the code generation is independent on the source of the meta model and represented via Exporters.
Code generation is done in so called Exporters. An Exporter is handed a
Hibernate Meta Model represented as a Configuration instance and it is then
the job of the exporter to generate a set of code artifacts.
The tools provides a default set of Exporter's which can be used in both Ant and the Eclipse UI. Documentation for these Exporters is in the Ant Tools and Eclipse Plugins chapters.
Users can provide their own customer Exporter's, either by custom classes implementing the
Exporter interface or simply be providing custom templates. This is documented at Section 4.4.7, “Generic Hibernate metamodel exporter (<hbmtemplate>)”
This chapter will introduce you to the functionality that Hibernate Tools provide within Eclipse. That is a set of wizards and editors for simplifying the work with Hibernate.
The following features are available in the Hibernate Tools Eclipse plugins:
Mapping Editor: An editor for Hibernate XML mapping files, supporting auto-completion and syntax highlighting. It also supports semantic auto-completion for class names and property/field names, making it much more versatile than a normal XML editor.
Hibernate Console: The console is a new perspective in Eclipse. It provides an overview of your Hibernate Console configurations, were you also can get an interactive view of your persistent classes and their relationships. The console allows you to execute HQL queries against your database and browse the result directly in Eclipse.
Configuration Wizards and Code generation: A set of wizards are provided with the Hibernate Eclipse tools; you can use a wizard to quickly generate common Hibernate configuration (cfg.xml) files, and from these you can code generate a series of various artifacts, there is even support for completely reverse engineer an existing database schema and use the code generation to generate POJO source files and Hibernate mapping files.
Eclipse JDT integration: Hibernate Tools integrates into the Java code completion and build support of Java in Eclipse. This gives you codecompletion of HQL inside Java code plus Hibernate Tools will add problem markers if your queries are not valid against the console configuration associated with the project.
Please note that these tools do not try to hide any functionality of Hibernate. The tools make working with Hibernate easier, but you are still encouraged/required to read the Hibernate Documentation to fully utilize Hibernate Tools and especially Hibernate it self.
Hibernate mapping files are used to specify how your objects are related to database tables.
For creating a skeleton mapping file, i. e. any .hbm.xml , Hibernate Tools provide a basic wizard which you can bring up by navigating New > Hibernate XML mapping file.
At first you'll be asked to specify the location and the name for a new mapping file. On the next dialog you should type or browse the class to map.
Pressing finish creates the file and opens it in the structured hbm.xml editor.
If you start the wizard from the selected class, all values will be detected there automatically.
To be able to reverse engineer, prototype queries, and of course to simply use Hibernate Core a hibernate.properties or hibernate.cfg.xml file is needed. The Hibernate Tools provide a wizard for generating the hibernate.cfg.xml file if you do not already have such one.
Start the wizard by clicking New > Other (Ctrl+N) , then Hibernate > Hibernate Configuration File (cfg.xml) and press Next . After selecting the wanted location for the hibernate.cfg.xml file, you will see the following page:
The contents in the combo boxes for the JDBC driver class and JDBC URL change automatically, depending on the Dialect and actual driver you have chosen.
Enter your configuration information in this dialog. Details about the configuration options can be found in Hibernate Reference Documentation.
Press Finish to create the configuration file, after optionally creating a Console configuration, the hibernate.cfg.xml will be automatically opened in an editor. The last option Create Console Configuration is enabled by default and when enabled, it will automatically use the hibernate.cfg.xml for the basis of a Console configuration.
A Console configuration describes how the Hibernate plugin should configure Hibernate and what configuration files, including which classpath are needed to load the POJO's, JDBC drivers etc. It is required to make usage of query prototyping, reverse engineering and code generation. You can have multiple named console configurations. Normally you would just need one per project, but more is definitely possible if your project requires this.
You create a console configuration by running the Console Configuration Wizard, shown in the following screenshot. The same wizard will also be used if you are coming from the hibernate.cfg.xml wizard and had enabled Create Console Configuration .
The wizard will look at the current selection in the IDE and try and auto-detect the settings which you then can just approve or modify to suit your needs.
The dialog consists of three tabs,
General
for the basic/required settings,
Classpath
for classpath and
Mappings
for additional mappings. The two latter ones are normally not required if you
specify a project and it has
/hibernate.cfg.xml
or
/META-INF/persistence.xml
in its project classpath.
The following table describes the available settings. The wizard can automatically detect default values for most of these if you started the wizard with the relevant java project or resource selected.
Table 3.1. Hibernate Console Configuration Parameters
|
Parameter |
Description |
Auto detected value |
|---|---|---|
|
Name |
The unique name of the console configuration |
Name of the selected project |
|
Project |
The name of a java project which classpath should be used in the console configuration |
Name of the selected project |
|
Type |
Choose between "Core", "Annotations" and "JPA". Note that the two latter requires running Eclipse IDE with a JDK 5 runtime, otherwise you will get classloading and/or version errors. |
No default value |
|
Property file |
Path to a hibernate.properties file |
First hibernate.properties file found in the selected project |
|
Configuration file |
Path to a hibernate.cfg.xml file |
First hibernate.cfg.xml file found in the selected project |
|
Persistence unit |
Name of the persistence unit to use |
No default value (lets Hibernate Entity Manager find the persistence unit) |
|
Naming strategy |
Fully qualified classname of a custom NamingStrategy. Only required if you use a special naming strategy. |
No default value |
|
Entity resolver |
Fully qualified classname of a custom EntityResolver. Only required if you have special xml entity includes in your mapping files. |
No default value |
The fallowing table specifies the parameters of the Classpath tab of the wizard.
Table 3.2. Hibernate Console Configuration Classpath
|
Parameter |
Description |
Auto detected value |
|---|---|---|
|
Classpath |
The classpath for loading POJO and JDBC drivers; only needed if the default classpath of the Project does not contain the required classes. Do not add Hibernate core libraries or dependencies, they are already included. If you get ClassNotFound errors then check this list for possible missing or redundant directories/jars. |
Empty |
|
Include default classpath from project |
When enabled the project classpath will be appended to the classpath specified above |
Enabled |
Parameters of the Mappings tab in the Hibernate Console Configuration wizard are explained below:
Table 3.3. Hibernate Console Configuration Mappings
|
Parameter |
Description |
Auto detected value |
|---|---|---|
|
Mapping files |
List of additional mapping files that should be loaded. Note: A hibernate.cfg.xml or persistence.xml can also contain mappings. Thus if these are duplicated here, you will get "Duplicate mapping" errors when using the console configuration. |
empty |
Clicking Finish creates the configuration and shows it in the Hibernate Configurations View.
A "click-and-generate" reverse engineering and code generation facility is available. This facility allows you to generate a range of artifacts based on database or an already existing Hibernate configuration, be that mapping files or annotated classes. Some of these are POJO Java source file, Hibernate .hbm.xml , hibernate.cfg.xml generation and schema documentation.
To start working with this process, start the Hibernate Code Generation which is available in the toolbar via the Hibernate icon or via the Run > Hibernate Code Generation menu item.
When you click on Open Hibernate Code Generation Dialog... the standard Eclipse launcher dialog will appear. In this dialog you can create, edit and delete named Hibernate code generation "launchers".
The first time you create a code generation launcher you should give it a meaningful name, otherwise the default prefix New_Generation will be used.
The "At least one exporter option must be selected" is just a warning stating that for this launch to work you need to select an exporter on the Exporter tab. When an exporter has been selected the warning will disappear.
The dialog also have the standard tabs Refresh and Common that can be used to configure which directories should be automatically refreshed and various general settings launchers, such as saving them in a project for sharing the launcher within a team.
On the Main tab you see the following fields:
Table 3.4. Code generation "Main" tab fields
|
Field |
Description |
|---|---|
|
Console Configuration |
The name of the console configuration which should be used when code generating |
|
Output directory |
Path to a directory where all output will be written by default. Be aware that existing files will be overwritten, so be sure to specify the correct directory. |
|
Reverse engineer from JDBC Connection |
If enabled, the tools will reverse engineer the database available via the connection information in the selected Hibernate Console Configuration and generate code based on the database schema. If not enabled, the code generation will just be based on the mappings already specified in the Hibernate Console configuration. |
|
Package |
The package name here is used as the default package name for any entities found when reverse engineering |
|
reveng.xml |
Path to a reveng.xml file. A reveng.xml file allows you to control certain aspects of the reverse engineering. e.g. how jdbc types are mapped to hibernate types and especially important which tables are included/excluded from the process. Clicking "setup" allows you to select an existing reveng.xml file or create a new one. See more details about the reveng.xml file in Chapter 5, Controlling reverse engineering. |
|
reveng. strategy |
If reveng.xml does not provide enough customization you can provide your own implementation of an ReverseEngineeringStrategy. The class needs to be in the classpath of the Console Configuration, otherwise you will get class not found exceptions. See Section 5.3, “Custom strategy” for details and an example of a custom strategy. |
|
Generate basic typed composite ids |
A table that has a multi-colum primary key a <composite-id> mapping will always be created. If this option is enabled and there are matching foreign-keys each key column is still considered a 'basic' scalar (string, long, etc.) instead of a reference to an entity. If you disable this option a <key-many-to-one> instead. Note: a <many-to-one> property is still created, but is simply marked as non-updatable and non-insertable. |
|
Detect optimistic lock columns |
Automatically detect optimistic lock columns. Controllable via reveng. strategy; the current default is to use columns named VERSION or TIMESTAMP. |
|
Detect many-to-many tables |
Automatically detect many-to-many tables. Controllable via reveng. strategy. |
|
Use custom templates |
If enabled, the Template directory will be searched first when looking up the templates, allowing you to redefine how the individual templates process the hibernate mapping model. |
|
Template directory |
A path to a directory with custom templates |
The Exporters tab is used to specify which type of code that should be generated. Each selection represents an Exporter that is responsible for generating the code, hence the name.
The following table describes in short the various exporters. Remember you can add/remove any Exporters depending on your needs.
Table 3.5. Code generation "Exporter" tab fields
|
Field |
Description |
|---|---|
|
Domain code |
Generates POJO's for all the persistent classes and components found in the given Hibernate configuration. |
|
DAO code |
Generates a set of DAO's for each entity found. |
|
Hibernate XML Mappings |
Generate mapping (hbm.xml) files for each entity. |
|
Hibernate XML Configuration |
Generate a hibernate.cfg.xml file. Used to keep the hibernate.cfg.xml update with any new found mapping files. |
|
Schema Documentation (.html) |
Generates a set of html pages that documents the database schema and some of the mappings. |
|
Generic Exporter (hbmtemplate) |
Fully customizable exporter which can be used to perform custom generation. |
Each Exporter listens to certain properties and these can be setup in the Properties section where you can add/remove predefined or customer properties for each of the exporters. The following table lists the time of writing predefined properties:
Table 3.6. Exporter Properties
|
Name |
Description |
|---|---|
|
jdk5 |
Generate Java 5 syntax |
|
ejb3 |
Generate EJB 3 annotations |
|
for_each |
Specifies for which type of model elements the exporter should create a file and run through the templates. Possible values are: entity, component, configuration |
|
template_path |
Custom template directory for this specific exporter. You can use Eclipse variables. |
|
template_name |
Name for template relative to the template path |
|
outputdir |
Custom output directory for this specific exporter. You can use Eclipse variables. |
|
file_pattern |
Pattern to use for the generated files, relatively for the output dir. Example: {package-name}/{class-name}.java . |
|
dot.executable |
Executable to run GraphViz (only relevant, but optional for Schema documentation) |
The Hibernate Mapping File editor provides XML editing functionality for the hbm.xml and cfg.xml files. The editor is based on the Eclipse WTP tools and extends its functionality to provide Hibernate specific code completion.
Package, class, and field completion is enabled for relevant XML attributes. The auto-completion detects its context and limits the completion for e.g. <property> and only shows the properties/fields available in the enclosing <class> , <subclass> etc. It is also possible to navigate from the hbm.xml files to the relevant class/field in java code.
This is done via the standard hyperlink navigation functionality in Eclipse; per default it is done by pressing F3 while the cursor is on a class/field or by pressing Ctrl and the mouse button to perform the same navigation.
For java completion and navigation to work the file needs to reside inside an Eclipse Java project, otherwise no completion will occur.
Java completion does not require a Hibernate console configuration to be used.
Table and column completion is also available for all table and column attributes.
Table/Column completion requires a proper configured hibernate console configuration and this configuration should be the default for the project where the hbm.xml resides.
You can check which console configuration is selected under the Properties of a project and look under the Hibernate Settings page. When a proper configuration is selected it will be used to fetch the table/column names in the background.
Currently it is not recommended to use this feature on large databases since it does not fetch the information iteratively. It will be improved in future versions.
The structured editor represents the file in the tree form. It also allows to modify the structure of the file and its elements with the help of tables provided on the right-hand area.
To open any mapping file in the editor, choose Open With > Hibernate 3.0 XML Editor option from the context menu of the file. The editor should look as follows:
For the configuration file you should choose Open With > Hibernate Configuration 3.0 XML Editoroption.
A reveng.xml file is used to customize and control how reverse engineering is performed by the tools. The plugins provide an editor to ease the editing of this file and hence used to configure the reverse engineering process.
The editor is intended to allow easy definition of type mappings, table include/excludes and specific override settings for columns, e.g. define an explicit name for a column when the default naming rules are not applicable.
Not all the features of the .reveng.xml file are exposed or fully implemented in the editor, but the main functionality is there. To understand the full flexibility of the reveng.xml , please see Section 5.2, “hibernate.reveng.xml file”
The editor is activated as soon as an .reveng.xml file is opened. To get an initial reveng.xml file the Reverse Engineering File Wizard can be started via Ctrl+N and Hibernate > Hibernate Reverse Engineering File (reveng.xml) then.
Or you can get it via the Code Generation Launcher by checking the proper section in the Main tab of the Hibernate Code Generation Wizard.
The following screenshot shows the Overview page where the wanted console configuration is selected (auto-detected if Hibernate 3 support is enabled for the project)
The Table Filter page allows you to specify which tables to include and exclude. Pressing Refresh shows the tables from the database that have not yet been excluded.
The Type Mappings page is used for specifying type mappings from JBDC types to any Hibernate type (including usertypes) if the default rules are not applicable. Here again to see the database tables press Refresh button underneath. More about type mappings you can find further in the Type Mappings section.
The Table and Columns page allows you to explicit set e.g. which hibernatetype and propertyname that should be used in the reverse engineered model. For more details on how to configure the tables while reverse engineering read the Specific table configuration section.
Now that you have configured all necessary parts, you can learn how to work with Hibernate Console Perspective.
The Hibernate Console Perspective combines a set of views which allow you to see the structure of your mapped entities/classes, edit HQL queries, execute the queries, and see the results. To use this perspective you need to create a Console configuration.
To view your new configuration and entity/class structure, switch to Hibernate Configurations View. Expanding the tree allows you to browse the class/entity structure and see the relationships.
The Console Configuration does not dynamically adjust to changes done in mappings and java code. To reload the configuration select the configuration and click the Reload button in the view toolbar or in the context menu.
Besides, it's possible to open source and mapping files for objects showed in Hibernate Configurations View. Just bring up the context menu for a necessary object and select Open Source File to see appropriate Java class or Open Mapping File to open a proper .hbm.xml.
In order to get a visual feel on how entities are related as well as view their structures, a Mapping Diagram is provided. It is available by right clicking on the entity you want a mapping diagram for and then choosing Open Mapping Diagram.
For better navigating on the Diagram use Outline view.
As in Hibernate Configurations View in Mapping Diagram it's also possible to open source/mapping file for a chosen object by selecting appropriate option in the context menu. If you ask to open source/mapping file by right clicking on any entity element, this element will be highlighted in the open file.
Queries can be prototyped by entering them in the HQL or Criteria Editor. The query editors are opened by right-clicking the Console Configuration and selecting either HQL Editor or Hibernate Criteria Editor. The editors automatically detect the chosen configuration.
If the menu item is disabled then you need at first to create a Session Factory. That is done by simply expanding the Session Factory node.
Not to enter manually simple queries like 'from Customer' or like on the figure below, you can do it with the editors help by brining up the context menu for a necessary item and choosing HQL Editor or Hibernate Criteria Editor .
Executing the query is done by clicking the green run button in the toolbar or pressing Ctrl+Enter .
Errors during creation of the Session Factory or running the queries (e.g. if your configuration or query is incorrect) will be shown in a message dialog or inclined in the view that detected the error, you may get more information about the error in the Error Log View on the right pane.
Results of a query will be shown in the Hibernate Query Result View and details of possible errors (syntax errors, database errors, etc.) can be seen in the Error Log View.
HQL queries are executed by default using list() thus without any
limit of the size of the output the query could return a large result set. You might run
out of memory. To avoid this you can put a value in the Max results field to reduce the
number of elements returned.
If the Hibernate Dynamic Query Translator View is visible while writing in the HQL Editor it will show the generated SQL for a HQL query.
The translation is done each time you stop typing into the editor, if there are errors in the HQL the parse exception will be shown embedded in the view.
It is possible to configure the eclipse plugin to route all logging made by the plugins and hibernate code it self to the Error Log View in Eclipse.
This is done by editing the hibernate-log4j.properties in org.hibernate.eclipse/ directory/jar . This file includes a default configuration that only logs WARN and above to a set of custom appenders (PluginFileAppender and PluginLogAppender). You can change these settings to be as verbose or silent as you please - see Hibernate Documentation for interesting categories and Log4j documentation.
Find more on how to configure logging via a log4j property file in Log4j 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 4.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 4.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 4.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 4.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 |