JBoss.orgCommunity Documentation

Hibernate Tools Reference Guide

Olga Chikvina

Svetlana Mukhina

Version: 4.1.x


1. Introduction
1.1. Key Features
1.2. Other relevant resources on the topic
2. Download and install Hibernate Tools
2.1. JBoss Tools
2.2. Eclipse IDE
2.2.1. Using Eclipse WTP
2.3. Ant
3. Code generation architecture
3.1. Hibernate Meta Model
3.2. Exporters
4. Eclipse Plugins
4.1. Introduction
4.1.1. Download base project
4.2. Creating a Hibernate Mapping File
4.3. Creating a Hibernate Configuration File
4.4. Hibernate Console Configuration
4.4.1. Creating a Hibernate Console Configuration
4.4.2. Modifying a Hibernate Console Configuration
4.4.3. Closing Hibernate Console Configuration
4.5. Reverse Engineering and Code Generation
4.5.1. Code Generation Launcher
4.5.2. Exporters
4.6. Hibernate Mapping and Configuration File Editor
4.6.1. Java property/class completion
4.6.2. Table/Column completion
4.6.3. Configuration property completion
4.7. Structured Hibernate Mapping and Configuration File Editor
4.8. JBoss Tools Properties Editor
4.9. Reveng.xml Editor
4.10. Hibernate Console Perspective
4.10.1. Viewing the entity structure
4.10.2. Prototyping Queries
4.10.3. Properties View
4.11. Hibernate:add JPA annotations refactoring
4.12. Enable debug logging in the plugins
4.12.1. Relevant Resources Links
4.13. Hibernate support for Dali plugins in Eclipse WTP
4.13.1. Creating JPA project with Hibernate support
4.13.2. Generating DDL and Entities
4.13.3. Hibernate Annotations Support
4.13.4. Relevant Resources Links
5. Ant Tools
5.1. Introduction
5.2. The <hibernatetool> Ant Task
5.2.1. Basic examples
5.3. Hibernate Configurations
5.3.1. Standard Hibernate Configuration (<configuration>)
5.3.2. Annotation based Configuration (<annotationconfiguration>)
5.3.3. JPA based configuration (<jpaconfiguration>)
5.3.4. JDBC Configuration for reverse engineering (<jdbcconfiguration>)
5.4. Exporters
5.4.1. Database schema exporter (<hbm2ddl>)
5.4.2. POJO java code exporter (<hbm2java>)
5.4.3. Hibernate Mapping files exporter (<hbm2hbmxml>)
5.4.4. Hibernate Configuration file exporter (<hbm2cfgxml>)
5.4.5. Documentation exporter (<hbm2doc>)
5.4.6. Query exporter (<query>)
5.4.7. Generic Hibernate metamodel exporter (<hbmtemplate>)
5.5. Using properties to configure Exporters
5.5.1. <property> and <propertyset>
5.5.2. Getting access to user specific classes
6. Controlling reverse engineering
6.1. Default reverse engineering strategy
6.2. hibernate.reveng.xml file
6.2.1. Schema Selection (<schema-selection>)
6.2.2. Type mappings (<type-mapping>)
6.2.3. Table filters (<table-filter>)
6.2.4. Specific table configuration (<table>)
6.3. Custom strategy
6.4. Custom Database Metadata
7. Controlling POJO code generation
7.1. The <meta> attribute
7.1.1. Recommendations
7.1.2. Advanced <meta> attribute examples

Hibernate Tools is a collection of tools 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.

The table below lists the key features found in Hibernate Tools.

Table 1.1. Key Functionality for Hibernate Tools

FeatureBenefitChapter

Code Generation through Ant Task

Allows to generate mapping or Java code through reverse engineering, schema generation and generation of other artifacts during the build process.

Chapter 5, Ant Tools

Wizards for creation purposes and code generation

A set of wizards are provided with the Hibernate Eclipse Tools™ to quickly create common Hibernate™ files such as configuration (cfg.xml) files, mapping files and reveng.xml as well. The Code Generation wizard helps by generating a series of various artifacts, and there is even support for completely reverse engineering an existing database schema.

Section 4.2, “Creating a Hibernate Mapping File” Section 4.3, “Creating a Hibernate Configuration File” Section 4.5.1, “Code Generation Launcher”

Mapping and Configuration files Editors

Support auto-completion and syntax highlighting. Editors also support semantic auto-completion for class names and property/field names, making it much more versatile than a normal XML editor.

Section 4.6, “Hibernate Mapping and Configuration File Editor”

Tools for organizing and controlling Reverse Engineering

The Code Generation wizard provides powerful functionality for generating a series of various artifacts such as domain model classes, mapping files, and annotated EJB3 entity beans, and the reveng.xml file editor provides control over this processes.

Section 4.5.1, “Code Generation Launcher” Section 4.9, “Reveng.xml Editor”

Hibernate Console

It is a new perspective in Eclipse which provides an overview of your Hibernate Console configurations, and 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.

Section 4.10, “Hibernate Console Perspective”

HQL Editor and Hibernate Criteria Editor

The editors are provided for writing, editing and executing HQL queries and criterias. They also have the ability to generate simple queries.

Section 4.10.2.1, “HQL Editor and Hibernate Criteria Editor”

Functional Mapping Diagram

Makes possible to visualize the structure of entities and the relationships between them.

Section 4.10.1.1, “Mapping Diagram”

Eclipse JDT integration

Hibernate Tools™ integrates into the Java code completion and build support for Java in Eclipse. This gives you HQL code completion inside Java code. Additionally, Hibernate Tools™ will display problem markers if your queries are not valid against the console configuration associated with the project.

 

The Hibernate Tools™ page on hibernate.org.

All JBDS™ release documentation can be found on the RedHat Documentation website.

There is some additional information on Hibernate™ on the JBoss Wiki page.

Nightly documentation builds are available here.

Hibernate Tools™ can be used "standalone" via Ant 1.6.x or fully integrated into an Eclipse + WTP based IDE, such as the case with JBDS/JBoss Tools™, or a default Eclipse + WTP installation. The following sections describe the install steps in these environments.

Note:

The Hibernate Tools 3.4.0™ (the current release version) requires Eclipse Helios (3.6).

The code generation mechanism in Hibernate Tools™ consists of a few core concepts. This section explains their overall structure, which is 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 the org.hibernate.mapping package 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 built in many ways:

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™.

The following drawing illustrates the core concepts:


The code generation is performed based on the Configuration model no matter which type of configuration has 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.

This chapter will introduce you to the set of wizards and editors provided by Hibernate Tools™ within Eclipse, which are designed to simplify working with Hibernate™.

Hibernate Eclipse Tools includes wizards for creating Hibernate mapping files, configuration files (.cfg.xml), reveng.xml files as well as wizards for adjusting Console Configuration and Code Generation. Special structured and XML editors and editors for executing HQL and Criteria queries are also provided in Hibernate Console. Refer to Section 1.1, “Key Features” to find all the benefits that are provided by these tools within Eclipse.

Note:

Please note that these tools do not try to hide any of Hibernates™ functionality; rather the tools make working with Hibernate™ easier. You are still encouraged to read the Hibernate Documentation in order to be able to fully utilize Hibernate Tools™ and especially Hibernate™ itself.

A Console configuration describes how the Hibernate plugin should configure Hibernate and what configuration files and classpaths are needed to load the POJO's, JDBC drivers etc. It is required to make use of query prototyping, reverse engineering and code generation. You can have multiple named console configurations. Normally you would just need one per project, but it is definitely possible to create more if required.

You can 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 the Create Console Configuration option.

The dialog consists of five tabs:


The following table describes the available settings on the Main tab. The wizard can automatically detect the default values for most of the settings if you started the wizard with the relevant Java project or resource selected.


Tip:

The two latter settings are usually not required if you specify a project that has a /hibernate.cfg.xml or /META-INF/persistence.xml file in its classpath.

  • The Options tab the optional settings


The next table describes the Hibernate Console Configuration options available on the Options tab.


  • Classpath for classpath


The following table specifies the parameters of the Classpath tab of the wizard.


  • Mappings for additional mappings


Parameters of the Mappings tab of the Hibernate Console Configuration wizard are explained below:


  • and the last tab Common


The Common tab allows you to define the general aspects of the launch configuration including storage location, console encoding and some others.

Clicking the Finish button creates the configuration and shows it in the Hibernate Configurations view.


When you created a Hibernate Console Configuration you can modify it in two ways:

Hibernate provides "click-and-generate" reverse engineering and code generation facilities. This allows you to generate a range of artifacts based on database or an existing Hibernate configuration, be that mapping files or annotated classes. Some of these are POJO Java source files, Hibernate .hbm.xml files, hibernate.cfg.xml generation and schema documentation.

To start working with this process, start the Hibernate Code Generation tool which is available from the toolbar via the Hibernate icon or via the RunHibernate Code Generation menu item.

When you click on the Open Hibernate Code Generation Dialog... option 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.

Tip:

The "At least one exporter option must be selected" warning indicates that for this launcher 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 has the standard Refresh and Common tabs that can be used to configure which directories should be automatically refreshed and various general settings for 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 4.6. Code generation "Main" tab fields

Field

Description

Console Configuration

The name of the console configuration that should be used when generating code

Output directory

The default location where all output will be written to. It's possible to enter absolute directory path, for example - d:/temp. 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 defined in the connection information in the selected Hibernate Console Configuration, and generate code based on the database schema. If not enabled, the code generation will be based on the existing mappings 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 process such as how JDBC types are mapped to Hibernate types, and which tables are included and excluded from the process (which is especially important). Clicking the Setup button allows you to select an existing reveng.xml file, or create a new one. See more details about the reveng.xml file in Chapter 6, Controlling reverse engineering.

reveng. strategy

If the reveng.xml file does not provide enough customization you can provide your own implementation of a ReverseEngineeringStrategy. The class needs to be in the classpath of the Console Configuration, otherwise you will get class not found exceptions. See Section 6.3, “Custom strategy” for details and an example of a custom strategy.

Generate basic typed composite ids

When a table that has a multi-column 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.

Detect one-to-one associations

Reverse engineering detects one-to-one associations via primary key and both the hbm.xml file and annotation generation generates the proper code for it.

The detection is enabled by default (except for Seam 1.2 and Seam 2.0) reverse engineering. For Hibernate Tools generation there is a checkbox to disable this feature if it is not required.

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 the 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 provides a short description of the various exporters. Remember you can add and remove any Exporters depending on your needs.


Each Exporter listens to certain properties which can be setup in the Properties section where you can add and remove predefined or customer properties for each of the exporters. The following table lists the time of writing predefined properties:


To add a property to the chosen Exporter click the Add button in the Properties section. In the resulting dialog you should select the property from the proposed list and the value for it.


Tip:

If the property is a directory, it is possible to browse directories in the Value field.


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.


A reveng.xml file is used to customize and control how reverse engineering is performed by the tools. The plugins provide an editor to assist in editing this file.

The editor is intended to allow easy definition of type mappings, table include and excludes, and specific override settings for columns, e.g. define an explicit name for a column when the default naming rules are not applicable.

The editor is activated as soon as a .reveng.xml file is opened. To create an initial reveng.xml file the Reverse Engineering File Wizard can be started by pressing Ctrl+N and then selecting HibernateHibernate Reverse Engineering File (reveng.xml).


Or you can get it via the Code Generation Launcher by checking the appropriate section in the Main tab of the Getting Hibernate Code Generation Wizard (see Figure 4.15, “Getting Hibernate Code Generation Launcher”).

The following screenshot shows the Overview page where the appropriate console configuration is selected (it is 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. Clicking the Refresh button shows the tables from the database that have not yet been excluded.


The Type Mappings page is used to specify type mappings from JBDC types to any Hibernate type (including user types) if the default rules are not applicable. To see the database tables press the Refresh button underneath. For more information on type mappings please see the Section 6.2.2, “Type mappings (<type-mapping>)” section.


The Table and Columns page allows you to explicitly set which details (e.g. which hibernatetype and propertyname) should be used in the reverse engineered model. For more details on how to configure the tables while reverse engineering read Section 6.2.4, “Specific table configuration (<table>)”.


The Hibernate Console Perspective combines a set of views which allow you to see the structure of your mapped entities and classes, edit HQL queries, execute the queries, and view the results. To use this perspective you need to create a Hibernate Console Configuration (see Section 4.4, “Hibernate Console Configuration” for more information).

To view your new configuration and entity or class structure, switch to the Hibernate Configurations View. Expanding the tree allows you to browse the class or entity structure, as well as view the relationships.


The Console Configuration does not dynamically adjust to changes performed 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.

It is possible to open source and mapping files for objects showed in the Hibernate Configurations View. Just bring up the context menu for an object and select Open Source File to see the appropriate Java class or Open Mapping File to open a .hbm.xml file.


In order to visualize 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 view a mapping diagram for and then selecting Mapping Diagram.


To make Mapping Diagram usage easier you can use the Rules, Grid, Snap to Geometry checkboxes in the View menu.


If you select the Rulers checkbox, the view print page scale will be added to the page. The numbers on the scale displays its size in inches. If you click on the scale a Ruler Guide will appear on the diagram. You can connect any diagram item to it. To connect the items you should move their tops to the Ruler Guide. And while moving the ruler guide, the items will be moved together with it as a whole.


If you select the Grid checkbox, a grid will appear on the diagram.


The Snap to Geometry checkbox allows you to align the diagram items with the grid.

For better navigating through the diagram use the Outline view, which is available in the structural and graphical modes.


To switch between the view modes, use the buttons in the top-right corner of the Outline view.


The options in the context menu of the mapping diagram are listed in the next table.


When you open the context menu for an item in the diagram, it differs quite significantly from the one described before.


The next table describes the additional options found in the mapping items context menu:


Tip:

All these context menu options are also available in the Outline view.

The following table lists the available keyboard shortcuts.


It is possible to save the diagram in the Eclipse workspace. Select FileSave As, and the wizard will ask you to specify the location within you project where you wish to save the file, and provide the name for the diagram. The default name is the item's names concatenated with the ampersand symbols. The file is saved with the .hibernate extension.


Note:

If you restart Eclipse with the mapping diagram opened, the mapping diagram will be restored with the message like on the figure below. To view the diagram content, you should refresh the view.



There are some useful commands in the toolbar.


They are described in the table below.


Queries can be prototyped by entering them into the HQL or Criteria Editor. To execute a query click the green run button in the editor toolbar, or press Ctrl+Enter.

To open the query editors right-click your projects Console Configuration and select HQL Editor (or Hibernate Criteria Editor).


Tip:

If the context menu items are disabled then you need at first to create a Session Factory. That is done by expanding the Session Factory node.

When they are opened, the editors they should automatically detect the chosen Console Configuration.

To generate a predefined query for any entity (or any entity child node) listed in the Session Factory you should double-click it. This will open the HQL Editor with the associated query.

Choosing HQL Editor in the context menu for any entity (or any entity child node) will also open the HQL Editor with the associated query. If you select Hibernate Criteria Editor in the context menu, it will open Hibernate Criteria Editor with the associated criteria.


It is also possible to copy a portion of code from a .java file into the HQL or Criteria editor. To do this make use of the Quick Fix option (Ctrl+1).


You can also update the original Java code with changes made in the HQL or Criteria editor. For that you should save your HQL/Criteria query and submit the replacement code when prompted by the confirmation dialog.


In addition, you can pin the HQL editor and Criteria editor as a tab in the Hibernate Query Result view. For that you need click on the Stick result to one tab button (). In this state query executions results will be shown in one tab (no more will be opened).

You are able to rename the Hibernate Query Result tab. Click the tab, and type a new name in the Property ViewTab name field.


Using this wizard you can add the following Hibernate annotations to a class: @Column, @Entity, @ManyToOne, @OneToMany, @OneToOne, @ManyToMany, @MappedSuperclass, @Id, @GeneratedValue, @Version

Note:

This section doesn't cover the definitions of the Hibernate annotations. For more information read the Hibernate Annotations Documentation.

To open this wizard you should right click the class you want to add the annotations to and select SourceGenerate Hibernate/JPA annotations from the context menu. You will see the Hibernate: add JPA annotations dialog.


The top section of this dialog lists all the classes that will be passed through refactoring. Next to the class you have selected, this list also displays its superclasses and the classes that the objects present in the current class as properties. If you want to add new classes or packages to the list, you should click the Back button. This will display the Add classes and packages page.


Here you can add additional classes or entire packages, and you can limit the dependencies depth by selecting the depth control option (you can find more information on this option in Section 4.2, “Creating a Hibernate Mapping File”). When you are finished click the Next button and you will be returned to The following classes will be changed page.

By default the tags are added to the fields of selected classes. You can change this option to Getters in the Preferred location of Annotations drop down list, which results in the annotations being added to the getter methods. If you choose Auto select from class preference then the annotations are added according to the position of the majority of the existing annotations.

If it is necessary to map your String properties to the columns that length differ from the default value (255), change the Default string length field and the @Column(length = your length) annotation will be created for every String property.

You can add optimistic locking capabilities to an entity bean by selecting the Enable optimistic locking checkbox. This operation will add the version property to all the selected classes. The property will be also annotated with @Version, and a getter and setter will be created. If the property is already exists, it won't be created, but the getters and setters will be generated. If there is already @MappedSuperclass annotation with @Version in the base class of the current class, @Version is not inserted into the current class.

After defining all the required settings click the Next button.


The view represents two windows: one with the source code and and the second with refactored one. With the help of the , , , buttons you can quickly navigate between the differences in the code. If you don't agree with some changes you can't undo them but you can remove the class from the list of classes that need refactoring.


To apply the changes click the Finish button.

Starting from version 3.0.0 Alpha1, JBoss Tools™ Hibernate plugins support Eclipse Dali integration, which makes it possible to use a Hibernate as a complete JPA development platform.

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.

Note:

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>

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.

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>

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>

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>

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"
 >

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().

When using the <jdbcconfiguration> tag, the Ant task will read the database metadata and then reverse engineer the database schema into a normal Hibernate Configuration. It is from this object (e.g. <hbm2java>) that other artifacts, such as .java and .hbm.xml, can be generated.

To govern this process Hibernate™ uses a reverse engineering strategy. A reverse engineering strategy is mainly called to provide more Java like names for tables, column and foreign keys into classes, properties and associations. It is also used to provide mappings from SQL types to Hibernate™ types.

The strategy can be customized by the user. This can be done by providing a custom reverse engineering strategy should the default strategy does not include the required functionality, or simply define a small component of the strategy and delegate the rest to the default strategy.

Further in this chapter we will discuss how you can configure the process of reverse engineering, what the default reverse engineering strategy includes, as well as some custom concepts.

A hibernate.reveng.xml file can provide a finer degree of control of the reverse engineering process. In this file you can specify type mappings and table filtering. This file can be created by hand (it's just basic XML) or you can use the Hibernate plugins, which provides a specialized editor.

Note:

Many databases have case-sensitive names, so if a table does not match, and you are sure it is not excluded by a <table-filter>, check that the case matches. Most databases stores table names in upper case.

Below you can see an example of a reveng.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering 
  SYSTEM "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>

<type-mapping>
 <!-- jdbc-type is name for java.sql.Types -->
 <sql-type jdbc-type="VARCHAR" length='20' hibernate-type="SomeUserType" /> 
 <sql-type jdbc-type="VARCHAR" length='1' hibernate-type="yes_no" />
 <!-- length, scale and precision can be used to specify the mapping precisely -->
 <sql-type jdbc-type="NUMERIC"  precision='1' hibernate-type="boolean" /> 
 <!-- the type-mappings are ordered. This mapping will be consulted last, 
  thus overridden by the previous one if precision=1 for the column -->
 <sql-type jdbc-type="NUMERIC"  hibernate-type="long" /> 
</type-mapping>

<!-- BIN$ is recycle bin tables in Oracle -->
<table-filter match-name="BIN$.*" exclude="true" /> 

<!-- Exclude DoNotWantIt from all catalogs/schemas -->
<table-filter match-name="DoNotWantIt" exclude="true" /> 

<!-- exclude all tables from the schema SCHEMA in catalog BAD. -->
<table-filter match-catalog="BAD" match-schema="SCHEMA" match-name=".*" exclude="true" /> 

<!-- table allows you to override/define how reverse engineering 
     is done for a specific table -->
<table name="ORDERS"> 
 <primary-key>
   <!-- setting up a specific id generator for a table -->
  <generator class="sequence">
    <param name="table">seq_table</param>
  </generator>
   <key-column name="CUSTID"/>
 </primary-key>
 <column name="NAME" property="orderName" type="string" />
 <!-- control many-to-one and set names for a specific named foreign key constraint -->
 <foreign-key constraint-name="ORDER_CUST">
   <many-to-one property="customer"/>
   <set property="orders"/>
 </foreign-key>
 <!-- can also control a pure (shared pk) one-to-one  -->
  <foreign-key constraint-name="ADDRESS_PERSON">
   <one-to-one exclude="false"/>
   <inverse-one-to-one exclude="true"/>
  </foreign-key>
</table>

</hibernate-reverse-engineering>

The <type-mapping> section specifies how the JDBC types found in the database should be mapped to Hibernate types. e.g. java.sql.Types.VARCHAR with a length of 1 should be mapped to the Hibernate type yes_no, or java.sql.Types.NUMERIC should generally just be converted to the Hibernate type long.

<type-mapping>
 <sql-type
  jdbc-type="integer value or name from java.sql.Types"
  length="a numeric value"
  precision="a numeric value"
  scale="a numeric value"
  not-null="true|false"  
  hibernate-type="hibernate type name"  
 />
</type-mapping>

The number of attributes specified and the sequence of the sql-type tags are important. This is because Hibernate™ will search for the most specific first, and if no specific match is found it will seek from top to bottom when trying to resolve a type mapping.

The following is an example of a type-mapping which shows the flexibility and importance of the ordering of the type mappings.

<type-mapping>
 <sql-type jdbc-type="NUMERIC" precision="15" hibernate-type="big_decimal"/>
 <sql-type jdbc-type="NUMERIC" not-null="true" hibernate-type="long" />
 <sql-type jdbc-type="NUMERIC" not-null="false" hibernate-type="java.lang.Long" />
 <sql-type jdbc-type="VARCHAR" length="1" not-null="true" 
       hibernate-type="java.lang.Character"/>
 <sql-type jdbc-type="VARCHAR" hibernate-type="your.package.TrimStringUserType"/>
 <sql-type jdbc-type="VARCHAR" length="1" hibernate-type="char"/>
 <sql-type jdbc-type="VARCHAR" hibernate-type="string"/>
</type-mapping>

The following table shows how this affects an example table named CUSTOMER:


The <table> tag allows you to explicitly define how a table should be reverse engineered. It allows control over the naming of a class for the table, provides a way to specify which identifier generator should be used for the primary key and more.

<table 
 catalog="catalog_name"
 schema="schema_name"
 name="table_name"
 class="ClassName"
>
 <primary-key.../>
 <column.../>
 <foreign-key.../>
 </table>

The <foreign-key> tag has two purposes. The first is to define foreign-keys in databases that does not support them or do not have them defined in their schema. The second is to define the name of the resulting properties (many-to-one, one-to-one and one-to-many's).

<foreign-key
  constraint-name="foreignKeyName"
  foreign-catalog="catalogName"
  foreign-schema="schemaName"
  foreign-table="tableName"
 >
 <column-ref local-column="columnName" foreign-column="foreignColumnName"/>
 <many-to-one 
   property="aPropertyName"
   exclude="true|false"/>
 <set 
   property="aCollectionName"
   exclude="true|false"
   
 <one-to-one 
   property="aPropertyName"
   exclude="true|false"/>
 <inverse-one-to-one
   property="aPropertyName"
   exclude="true|false"/>
   </foreign-key>

Table 6.6. Foreign-key attributes

Attribute nameDefinitionAttribute use

constraint-name

Name of the foreign key constraint. Important when naming many-to-one, one-to-one and set. It is the constraint-name that is used to link the processed foreign-keys with the resulting property names.

Required

foreign-catalog

Name of the foreign table's catalog. (Only relevant if you want to explicitly define a foreign key).

Optional

foreign-schema

Name of the foreign table's schema. (Only relevant if you want to explicitly define a foreign key).

Optional

foreign-table

Name of the foreign table. (Only relevant if you want to explicitly define a foreign key).

Optional

column-ref

Defines the foreign-key constraint between a local-column and foreign-column name. (Only relevant if you want to explicitly define a foreign key).

Optional

many-to-one

Defines that a many-to-one should be created and the property attribute specifies the name of the resulting property. Exclude can be used to explicitly define that it should be created or not.

Optional

set

Defines that a set should be created based on this foreign-key and the property attribute specifies the name of the resulting (set) property. Exclude can be used to explicitly define that it should be created or not.

Optional

one-to-one

Defines that a one-to-one should be created and the property attribute specifies the name of the resulting property. Exclude can be used to explicitly define that it should be created or not.

Optional

inverse-one-to-one

Defines that an inverse one-to-one should be created based on this foreign-key and the property attribute specifies the name of the resulting property. Exclude can be used to explicitly define that it should be created or not.

Optional


When using the <hbm2java> tag or the Eclipse plugin to generate POJO Java code you have the ability to control certain aspects of the code generation process. This is primarily done with the <meta> tag in the mapping files. The following section describes the possible <meta> tags and their use.

The <meta> tag is a simple way of annotating the hbm.xml file with information, so tools have a natural place to store and read information that is not directly related to the Hibernate core.

As an example, you can use the <meta> tag to tell the <hbm2java> tag to only generate "protected" setters, have classes always implement a certain set of interfaces, have them extend a certain base class and more.

The following example shows how to use various <meta> attributes and the resulting Java code.

<class name="Person">
    <meta attribute="class-description">
        Javadoc for the Person class
        @author Frodo
    </meta>
    <meta attribute="implements">IAuditable</meta>
    <id name="id" type="long">
        <meta attribute="scope-set">protected</meta>
        <generator class="increment"/>
    </id>
    <property name="name" type="string">
        <meta attribute="field-description">The name of the person</meta>
    </property>
</class>

The above hbm.xml file will produce something like the following (the code has been abbreviated for clarity). Notice the Javadoc comment and the protected set methods:

// default package

import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

/** 
 *         Javadoc for the Person class
 *         @author Frodo
 */
public class Person implements Serializable, IAuditable {

    public Long id;

    public String name;

    public Person(java.lang.String name) {
        this.name = name;
    }

    public Person() {
    }

    public java.lang.Long getId() {
        return this.id;
    }

    protected void setId(java.lang.Long id) {
        this.id = id;
    }

    /** 
     * The name of the person
     */
    public java.lang.String getName() {
        return this.name;
    }

    public void setName(java.lang.String name) {
        this.name = name;
    }

}

Attributes declared via the <meta> tag "inherited" inside an hbm.xml file by default.

What does that mean? As an example if you want to have all your classes implement IAuditable then you just add <meta attribute="implements">IAuditable</meta> in the top of the hbm.xml file, just after <hibernate-mapping>. Now all classes defined in that hbm.xml file will implement IAuditable.

Note:

This applies to all <meta>-tags. Thus it can also be used to specify that all fields should be declare protected, instead of the default private. This is done by adding <meta attribute="scope-field">protected</meta> just under the <class> tag, and all fields of that class will be protected.

To avoid having a <meta> tag inherited then you can specify inherit = "false" for the attribute. For example <meta attribute = "scope-class" inherit = "false">public abstract</meta> will restrict the "class-scope" to the current class, not the subclasses.

The following are some good practices to employ when using <meta> attributes.

In the following example we have two entities with a bi-directional association between them and define the use-in-string and use-in-equals meta attributes at the class scope level the meta attributes:

<hibernate-mapping>
  <class name="Person">
    <meta attribute="use-in-tostring">true</meta>
    <meta attribute="use-in-equals">true</meta>
    ...
  </class>
</hibernate-mapping>

Here is the Event.hbm file:

<hibernate-mapping>              
  <class name="events.Event" table="EVENTS">
    <meta attribute="use-in-tostring">true</meta>
    <meta attribute="use-in-equals">true</meta>                  
    <id name="id" column="EVENT_ID">
        <generator class="native"/>
    </id>
    <property name="date" type="timestamp" column="EVENT_DATE"/>
    <property name="title"/>
    <set name="participants" table="PERSON_EVENT" inverse="true">
        <key column="EVENT_ID"/>
        <many-to-many column="PERSON_ID" class="events.Person"/>
    </set>                    
  </class>
</hibernate-mapping>

In this situation the <hbm2java> tag will assume you want to include all properties and collections in the toString() and equals() methods. This can result in infinite recursive calls.

To remedy this you have to decide which side of the association will include the other part (if at all) in the toString() and equals() methods. Therefore it is not a good practice to define these meta attributes at the class scope, unless you are defining a class without bi-directional associations.

Instead it is recommended that the meta attributes are defined at the property level, like so:

<hibernate-mapping>             
  <class name="events.Event" table="EVENTS">                  
    <id name="id" column="EVENT_ID">
        <meta attribute="use-in-tostring">true</meta>
        <generator class="native"/>
    </id>
    <property name="date" type="timestamp" column="EVENT_DATE"/>
    <property name="title">
      <meta attribute="use-in-tostring">true</meta>
      <meta attribute="use-in-equals">true</meta>      
    </property>
    <set name="participants" table="PERSON_EVENT" inverse="true">
        <key column="EVENT_ID"/>
        <many-to-many column="PERSON_ID" class="events.Person"/>
    </set>                    
  </class>
</hibernate-mapping>

and for Person:

<hibernate-mapping>
    <class name="Person">
    <meta attribute="class-description">
        Javadoc for the Person class
        @author Frodo
    </meta>
    <meta attribute="implements">IAuditable</meta>
    <id name="id" type="long">
        <meta attribute="scope-set">protected</meta>
        <meta attribute="use-in-tostring">true</meta>        
        <generator class="increment"/>
    </id>
    <property name="name" type="string">
        <meta attribute="field-description">The name of the person</meta>
        <meta attribute="use-in-tostring">true</meta>
    </property>
  </class>
</hibernate-mapping>

This section shows an example for using meta attributes (including user specific attributes) together with the code generation features in Hibernate Tools™.

The example shown below automatically inserts some pre and post conditions into the getter and setter methods of the generated POJO.

With <meta attribute="class-code"> you can add additional methods on a given class. However, such <meta> attributes can not be used at a property scope level and Hibernate Tools does not provide such <meta> attributes.

A possible solution for this is to modify the Freemarker templates responsible for generating the POJOs. If you look inside the hibernate-tools.jar archive, you can find the template pojo/PojoPropertyAccessor.ftl.

As its name indicates, this file is used to generate property accessors for POJOs.

Extract the PojoPropertyAccessor.ftl file into a local folder e.g. ${hbm.template.path}, respecting the whole path, for example: ${hbm.template.path}/pojo/PojoPropertyAccessor.ftl.

The contents of the file will be something like this:

<#foreach property in pojo.getAllPropertiesIterator()>
    ${pojo.getPropertyGetModifiers(property)} 
    ${pojo.getJavaTypeName(property, jdk5)} 
    ${pojo.getGetterSignature(property)}() {
        return this.${property.name};
    }
    
    ${pojo.getPropertySetModifiers(property)} void set${pojo.getPropertyName(property)}
        (${pojo.getJavaTypeName(property, jdk5)} ${property.name}) 
    {
        this.${property.name} = ${property.name};
    }
</#foreach>

We can add pre and post conditions on our set method generation just by adding a little Freemarker syntax to the above source code:

<#foreach property in pojo.getAllPropertiesIterator()>
    ${pojo.getPropertyGetModifiers(property)} 
    ${pojo.getJavaTypeName(property, jdk5)} 
    ${pojo.getGetterSignature(property)}()
    {
        return this.${property.name};
    }
    
    ${pojo.getPropertySetModifiers(property)} void set${pojo.getPropertyName(property)}
        (${pojo.getJavaTypeName(property, jdk5)} ${property.name}) 
        {
      <#if pojo.hasMetaAttribute(property, "pre-cond")> 
       ${c2j.getMetaAsString(property, "pre-cond","\n")} 
      </#if>      
      this.${property.name} = ${property.name};
      <#if pojo.hasMetaAttribute(property, "post-cond")> 
       ${c2j.getMetaAsString(property, "post-cond","\n")} 
      </#if>        
}
</#foreach>

Now if in any .hbm.xml file we define the <meta> attributes: pre-cond or post-cond, and their contents will be generated into the body of the relevant set method.

As an example let us add a pre-condition for the name property which will prevent the Person class from having an empty name. To achieve this we have to modify the Person.hbm.xml file like so:

<hibernate-mapping>
  <class name="Person">
  <id name="id" type="long">        
      <generator class="increment"/>
  </id>
  <property name="firstName" type="string">
      <meta attribute="pre-cond">
      if ((firstName != null) &amp;&amp; (firstName.length() == 0) ) {
        throw new IllegalArgumentException("firstName can not be an empty String");
      }
      </meta>
  </property>
</class>
</hibernate-mapping>

Finally we have to generate the Person.java class. For this we can use either Eclipse or Ant, as long as you remember to set or fill in the templatepath setting. For Ant we configure the <hibernatetool> task via the templatepath attribute as in:

    <target name="hbm2java">
        <taskdef name="hibernatetool"
          classname="org.hibernate.tool.ant.HibernateToolTask"
          classpathref="lib.classpath"/>
        <hibernatetool destdir="${hbm2java.dest.dir}"
          templatepath="${hbm.template.path}">
          <classpath>
            <path refid="pojo.classpath"/>
          </classpath>        
          <configuration>
            <fileset dir="${hbm2java.src.dir}">
              <include name="**/*.hbm.xml"/>
            </fileset>
          </configuration>
          <hbm2java/>
        </hibernatetool>
    </target>

Invoking the target <hbm2java> will generate file Person.java in ${hbm2java.dest.dir}:

// default package
import java.io.Serializable;
public class Person implements Serializable {

    public Long id;

    public String name;

    public Person(java.lang.String name) {
        this.name = name;
    }

    public Person() {
    }

    public java.lang.Long getId() {
        return this.id;
    }

    public void setId(java.lang.Long id) {
        this.id = id;
    }
    
    public java.lang.String getName() {
        return this.name;
    }

    public void setName(java.lang.String name) {
        if ((name != null) &amp;&amp; (name.length() == 0)) {
            throw new IllegalArgumentException("name can not be an empty String");
        }
        this.name = name;
    }
    }

In conclusion, this document is intended to introduce you to Hibernate plugin specific features related to tools both for the Eclipse and Ant tasks.

In Chapter 4, Eclipse Plugins you've learned about a set of wizards for creating Mapping files, Configuration files, Console Configurations, become familiar with Mapping and Configuration files editors, tooling for organizing and controlling Reverse Engineering, Hibernate Console and Mapping diagrams.

The rest chapters have explored the use of the Hibernate Tools™ via Ant tasks.

Please visit JBoss Tools Users Forum to leave questions or/and suggestions on the topic. Your feedback is always appreciated.