JBoss.orgCommunity Documentation
Version: 3.3.0.M5
Copyright © 2007, 2008, 2009, 2010, 2011 JBoss by Red Hat
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
Feature | Benefit | Chapter |
---|---|---|
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 ( | 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 | 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.
The Hibernate Tools 3.4.0™ (the current release version) requires Eclipse Helios (3.6).
JBoss Tools 3.4.0™ (the latest release) includes Hibernate Tools 3.3.0™ and thus no additional steps are required beyond downloading and installing JBoss Tools™. If you need to update to a newer version of the Hibernate Tools™ just follow the instructions in Section 2.2, “Eclipse IDE”.
To install the Hibernate Tools™ into any Eclipse 3.6™ based IDE you can either use the JBoss Tools Update Site.
If you need more detailed instructions on plugin installation 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 the use of the update manager.
To use the tools via Ant™ you need the hibernate-tools.jar
file and associated libraries. The libraries are included in the distribution from the Hibernate™ website and the Eclipse™ update site. 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 the Hibernate Tools™ via Ant™ tasks is described in Chapter 5, Ant Tools.
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 model represented by the Configuration
class can be built in many ways:
The tool provides a default set of Exporter's which can be used in both Ant and the Eclipse UI. Documentation for these Exporters can be found in Chapter 5, Ant Tools and Chapter 4, Eclipse Plugins.
Users can provide their own custom Exporter's, either through custom classes implementing the Exporter
interface or simply through custom templates. This is documented at in Section 5.4.7, “Generic Hibernate metamodel exporter (<hbmtemplate>)”.
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.
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.
You can download the example projects that are used in this chapter.
A JPA base project is available on the documentation resources page together with a base Java project.
Also you need start the database.
The steps for running the database are documented in the Getting Started Guide.
Hibernate mapping files are used to specify how your objects relate to database tables.
Using the depth control option you can define the dependency depth used when choosing classes.
The next wizard page lists the mappings to be generated. You can see the Customers, Orders, Productlines and Products classes added under depth control driving.
This wizard page display a preview of the generated .hbm
files.
Clicking the
button creates the files.Start the wizard by clicking Ctrl+N), then select → and click the button.
→ → (The contents in the comboboxes 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.
Click the hibernate.cfg.xml
file 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
file for the basis of a Console configuration.
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.
Table 4.1. Hibernate Console Configuration Parameters
Parameter |
Description |
Default value |
---|---|---|
Name |
The unique name of 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 (or newer) runtime, otherwise you will get class loading and version errors. You will also need to select the version of Hibernate your application server has (3.5, 3.6 or 4.0). Select a version from the drop-down box labelled Hibernate Version. |
Core and Hibernate Version: 3.5 |
Project |
The name of a Java project whose classpath should be used in the console configuration |
Name of the selected project |
Database connection |
DTP provided connection that you can use instead of what is defined in the |
[Hibernate Configured connection] |
Property file |
Path to a |
First |
Configuration file |
Path to a |
First |
Persistence unit |
Name of the persistence unit to use |
No default value (let Hibernate Entity Manager find the persistence unit or it can be defined manually using the button) |
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.
Table 4.2. Hibernate Console Configuration Options
Parameter |
Description |
Auto detected value |
---|---|---|
Database dialect |
Define a database dialect. It is possible either to enter your own value or choose from list. |
No default value |
Naming strategy |
Fully qualified class name of a custom |
No default value |
Entity resolver |
Fully qualified class name of a custom |
No default value |
Classpath for classpath
The following table specifies the parameters of the Classpath tab of the wizard.
Table 4.3. 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 or JAR files. |
Empty |
Include default classpath from project |
When enabled the project classpath will be appended to the classpath specified above |
Enabled |
Mappings for additional mappings
Parameters of the Mappings tab of the Hibernate Console Configuration wizard are explained below:
Table 4.4. Hibernate Console Configuration Mappings
Parameter |
Description |
Auto detected value |
---|---|---|
Mapping files |
List of additional mapping files that should be loaded. Note: A |
empty |
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 Hibernate Configurations view.
button creates the configuration and shows it in theWhen you created a Hibernate Console Configuration you can modify it in two ways:
You will then see the Edit Configuration Wizard, which is similar to Create Console Configuration, described in Section 4.4.1, “Creating a Hibernate Console Configuration”.
Use the Properties view to modify the Console Configuration properties.
The following table describes the available settings in the Properties view. Most properties can be changed by left clicking on them, but some can not.
Table 4.5. Properties
Property |
Description |
Is Changeable |
---|---|---|
Additional mapping files |
Count of additional mapping files that should be loaded. |
False |
Configuration file |
Path to a |
False |
Connection |
DTP provided connection that you can use instead of what is in the |
True |
Name |
The unique name of the console configuration |
True |
Project |
The name of a Java project which classpath should be used in the console configuration |
True |
Properties file |
Path to a |
False |
Type |
Choose between "CORE", "ANNOTATIONS" and "JPA" according to the method of relational mapping you want to use. Note, the two latter requires running Eclipse IDE with a JDK 5 runtime, otherwise you will get class loading and/or version errors. |
True |
When you click on the 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.
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 - |
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. strategy |
If the |
Generate basic typed composite ids |
When a table that has a multi-column primary key a |
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 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 following table provides a short description of the various exporters. Remember you can add and remove any Exporters depending on your needs.
Table 4.7. 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 ( |
Hibernate XML Configuration |
Generate a |
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 that can be used to perform custom generation. |
Schema Export (.ddl) |
Generates the appropriate SQL DDL and allows you to store the result in a file or export it directly to the database. |
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:
Table 4.8. 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: |
dot.executable |
Executable to run GraphViz (only relevant, but optional for Schema documentation) |
drop |
Output will contain drop statements for the tables, indices and constraints |
delimiter |
If specified the statements will be dumped to this file |
create |
Output will contain create statements for the tables, indices and constraints |
scriptToConsole |
The script will be output to Console |
exportToDatabase |
Executes the generated statements against the database |
outputFileName |
If specified the statements will be dumped to this file |
haltOnError |
Halts the build process if an error occurs |
format |
Applies basic formatting to the statements |
schemaUpdate |
Updates a schema |
If the property is a directory, it is possible to browse directories in the Value field.
This is done via the standard hyperlink navigation functionality in Eclipse. By default this is done by pressing F3 while the cursor is on a class or field, or by pressing Ctrl and the mouse button.
For Java completion and navigation to work the file needs to reside inside an Eclipse Java project, otherwise the feature is not available.
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 and Column completion requires a properly 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 in the Properties of a project under the Hibernate Settings page. When a proper configuration is selected it will be used to fetch the table and 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. This will be improved in future versions.
To open any mapping file in the editor, select → from the context menu of the file. The editor is shown in the following image:
For the configuration file you should select
→ .To add the property in the Properties view, click the button.
In the Name field press Ctrl+Space to invoke the content assist. It will suggest 'hibernate.'
which is the prefix for all hibernate properties. After selecting 'hibernate.'
and invoking the content assist again, other prefixes and properties are displayed as the proposals, with a description for each one.
When invoking the content assist in the Value field, it also provides a list of proposals.
In the Source view of the editor, content assist can also be invoked both for properties names and values:
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
file, please see Section 6.2, “hibernate.reveng.xml file”
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 → .
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 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 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).
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 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 to see the appropriate Java class or to open a .hbm.xml
file.
To make Mapping Diagram usage easier you can use the Rules, Grid, Snap to Geometry checkboxes in the 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.
Table 4.9. Context Menu Options of the Mapping Diagram
Icon |
Command |
Description |
---|---|---|
|
Show|Hide connections | Allows you to select what types of connections should be shown on the diagram:
|
|
Select All |
Selects all the diagram elements |
|
Auto layout |
Used to dispose all the items in the diagram in a standard manner |
|
Export as Image |
Allows the diagram to be exported as a |
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:
Table 4.10. Extra Options in the Context Menu of Mapping Item
Icon |
Command |
Description |
---|---|---|
|
Open Source File |
Opens the source file for a chosen object or element. The selected element will be highlighted in the open file. |
|
Open Mapping File |
Opens a mapping file for a chosen object or element. The selected element will be highlighted in the open file. |
|
Show|Hide shape(s) |
Used to hide or show an item on the mapping diagram |
|
Expand|Collapse shape(s) |
Used to expand and collapse fields displayed by the item |
All these context menu options are also available in the Outline view.
The following table lists the available keyboard shortcuts.
Table 4.11. Hibernate Mapping Diagram Shortcut Keys
Command |
Binding |
---|---|
Scroll the diagram content |
Ctrl+Shift+arrows |
Collapse or Expand selected item(s) |
Enter |
Show or Hide selected item(s) |
+ |
Sort items in alphabetical order or return to the initial state |
Space |
Navigate between the items |
Arrows |
It is possible to save the diagram in the Eclipse workspace. Select .hibernate
extension.
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.
Table 4.12. Command in Diagram View Toolbar
Icon |
Command |
Description |
---|---|---|
|
Refresh Visual Mapping |
It will update the Mapping Diagram the if Console Configuration was changed. |
|
Zoom Box |
Used to define scale of the diagram. It is also used for printing Mapping Diagrams. If you want to print the whole diagram to one page, you need select the Page option in the Zoom Box drop down list. |
|
Auto layout |
Used to arrange all diagram items in a standard manner. |
|
Show|Hide connections |
Used to show or hide a connection on the diagram. You can also choose what type of connections must be present on the diagram (Property Mappings, Class Mappings, Associations or Foreign key constraints). |
|
Expand|Collapse |
Used for expanding or collapsing fields of the item. |
|
Show|Hide shape(s) |
Used to hide or show an item on the mapping diagram. |
To open the query editors right-click your projects Console Configuration and select (or ).
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 Hibernate Criteria Editor with the associated criteria.
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 in the context menu, it will open
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 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 → field.
It also displays the structure of any persistent object selected in the Hibernate Query Results View. Editing is not yet supported.
You can also use Properties view when clicking on the configuration itself in Hibernate Configuration view (see Section 4.4.2, “Modifying a Hibernate Console Configuration ”).
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 Hibernate: add JPA annotations dialog.
→ from the context menu. You will see theThe 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 Add classes and packages page.
button. This will display theHere 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 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.
After defining all the required settings click the 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
button.
This is done by editing the hibernate-log4j.properties
file in the org.hibernate.eclipse/
directory or 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 the Hibernate Documentation for more information on logging categories and Log4j documentation.
When starting a new JPA project by selecting JPA Perspective), the first wizard page is shown in the image below. → → → (or simply → in the
You can select a target runtime and change the project configuration, or you can leave everything as it is.
On the JPA Facet page you should choose Hibernate as a target platform. Also select the proper database connection, if it is defined, or add a new one by clicking the Add connection link.
Clicking the
button will generate the project.If you choose Hibernate as a platform while creating a JPA/Dali project, a Hibernate Console Configuration for the project is created automatically when the wizard is finished. It allows all the Hibernate Tools features to be used without any additional setup.
By enabling Hibernate platform specific features you can now generate DDL and Entities. To do that select the → options in the context menu of your JPA project.
Remember to put the appropriate database driver to the classpath of your project.
The Generate Entities wizard will first ask you to choose the directory where all output will be written.
To generate entities you can use:
In this way you can enable Hibernate runtime support in Eclipse JPA projects.
This chapter demonstrates how to use Hibernate Tools via Ant tasks.
The hibernate-tools.jar
file, available from tools.hibernate.org, contains the core code for Hibernate Tools™. It is used as the basis for both the Ant tasks described in this document and the Eclipse plugins available as part of JBoss Developer Studio. The hibernate-tools.jar
file is located in your Eclipse plugins directory at /plugins/org.hibernate.eclipse.x.x.x/lib/tools/hibernate-tools.jar
.
This jar is 100% independent from the Eclipse platform and can thus be used independently of Eclipse.
There may be incompatibilities with respect to the hibernate3.jar
bundled with the tools and your own JAR. To avoid any confusion it is recommended that you use the hibernate3.jar
and hibernate-annotations.jar
files bundled with the tools when you want to use the Ant tasks. Do not worry about using the JAR's from a later version of Hibernate (e.g. Hibernate 3.2) with a project using an earlier version of Hibernate (e.g. a Hibernate 3.1) since the generated output will work with previous Hibernate 3 versions.
<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" />
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 destdir="${build.dir}/generated"> <classpath> <path location="${build.dir}/classes"/> </classpath> <configuration configurationfile="hibernate.cfg.xml"/> <hbm2java/> </hibernatetool>
<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>
<configuration configurationfile="hibernate.cfg.xml" propertyfile="hibernate.properties" entityresolver="EntityResolver classname" namingstrategy="NamingStrategy classname" > <fileset...> </configuration>
<hibernatetool destdir="${build.dir}/generated"> <annotationconfiguration configurationfile="hibernate.cfg.xml"/> <!-- list exporters here --> </hibernatetool>
<jdbcconfiguration ... packagename="package.name" revengfile="hibernate.reveng.xml" reversestrategy="ReverseEngineeringStrategy classname" detectmanytomany="true|false" detectoptmisticlock="true|false" > ... </jdbcconfiguration>
<hbm2ddl export="true|false" update="true|false" drop="true|false" create="true|false" outputfilename="filename.ddl" delimiter=";" format="true|false" haltonerror="true|false" >
<hbm2hbmxml/>
<query destfile="filename"> <hql>[a HQL query string]</hql> </query>
<hibernatetool> <configuration configurationfile="hibernate.cfg.xml"/> <query>from java.lang.Object</query> </hibernatetool>
<hibernatetool> <configuration configurationfile="hibernate.cfg.xml"/> <query destfile="queryresult.txt"> <hql>select c.name from Customer c where c.age > 42</hql> <hql>from Cat</hql> </hibernatetool>
<hbmtemplate filepattern="{package-name}/{class-name}.ftl" template="somename.ftl" exporterclass="Exporter classname" />
You can read more about Velocity and Freemarker to find out why using the latter is better or refer to Max Andersens discussion on the topic in "A story about FreeMarker and Velocity".
<property key="descriptors" value="true"/>
Usually using the <property>
tag is enough when specifying the properties required by the exporters. Still, the Ant tools supports the notion of a <propertyset>
which is used for grouping a set of properties. More about the functionality of <propertyset>
is can be found in the Ant manual.
<property key="hibernatetool.sometool.toolclass" value="x.y.z.NameOfToolClass"/>
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.
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>
<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>
<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
:
<table-filter match-catalog="catalog_matching_rule" match-schema="schema_matching_rule" match-name="table_matching_rule" exclude="true|false" package="package.name" />
<table catalog="catalog_name" schema="schema_name" name="table_name" class="ClassName" > <primary-key.../> <column.../> <foreign-key.../> </table>
<primary-key <generator class="generatorname"> <param name="param_name">parameter value</param> </generator> <key-column...> </primary-key>
<column name="column_name" jdbc-type="java.sql.Types type" type="hibernate_type" property="propertyName" exclude="true|false" />
<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>
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 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>
// 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
.
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.
<hibernate-mapping> <class name="Person"> <meta attribute="use-in-tostring">true</meta> <meta attribute="use-in-equals">true</meta> ... </class> </hibernate-mapping>
<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>
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>
<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>
On www.hibernate.org you can find more in-depth explanation on the subject of equals()
and hashcode()
methods.
As its name indicates, this file is used to generate property accessors for POJOs.
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>
<#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>
<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) && (firstName.length() == 0) ) { throw new IllegalArgumentException("firstName can not be an empty String"); } </meta> </property> </class> </hibernate-mapping>
<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) && (name.length() == 0)) { throw new IllegalArgumentException("name can not be an empty String"); } this.name = name; } }
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.