Hibernate Tools Reference Guide

Hibernate Tools Reference Guide

Preface

Hibernate Tools is a toolset for Hibernate 3 and related projects. The tools provide Ant tasks and Eclipse plugins for performing reverse engineering, code generation, visualization and interaction with Hibernate.

Chapter 1. Download and install Hibernate Tools

Hibernate tools can be used "standalone" via Ant 1.6.x or fully integrated into a Eclipse 3.1.x based IDE, such as JBoss Eclipse IDE or a default Eclipse 3.1.x installation. The following describes the install steps in these environments.

1.1. JBoss Eclipse IDE

JBoss Eclipse IDE 1.5.x includes Hibernate Tools and thus nothing is required besides downloading and installing JBoss Eclipse IDE. If you need to update to a newer version of the Hibernate Tools just follow the instructions in the Eclipse IDE section.

1.2. Eclipse IDE

To install into any Eclipse 3.1.x based Eclipse IDE you can either download the Hibernate Tools distribution from the Hibernate website or use the Eclipse updatesite (see http://tools.hibernate.org for download links).

If you download the Hibernate Tools distribution you need to place the /plugins and /feature directory into your eclipse directory or eclipse extensions directory. Sometimes Eclipse does not automatically detect new plugins and thus the tools will not be activated. To ensure eclipse sees these changes run eclipse with the -clean option. E.g. eclipse -clean Using the updatesite does not require any additional steps.

Tip: If you need more basic instructions on installing plugins and general usage of eclipse then check out https://eclipse-tutorial.dev.java.net/ and especially https://eclipse-tutorial.dev.java.net/visual-tutorials/updatemanager.html which covers using the update manager.

1.2.1. Usage of Eclipse WTP

The Hibernate tools plugins currently uses WTP 1.0 which at this time is the latest stable release from the Eclipse Webtools project.

Because the WTP project have not proper versioned their plugins there might exist WTP plugins in your existing eclipse directory from other Eclipse based projects that are from an earlier WTP release but has either the same version number or higher. It is thus recommended that if you have issues with WTP provided features to try and install the plugins on a clean install of eclipse to ensure there are no version-collisions.

The tools only include a subset of the WTP 1.0 plugins, thus if you want full access to the WTP functionallity the full WTP 1.0 SDK can be installed on top of the plugins without any problems.

1.3. Ant

To use the tools via Ant you need the hibernate-tools.jar and associated libraries. The libraries are included in the distribution from the Hibernate website and the Eclipse updatesite. The libraries are located in the eclipse plugins directory at /plugins/org.hibernate.eclipse.x.x.x/lib/tools/. These libraries are 100% independent from the eclipse platform. How to use these via ant tasks are described in the Ant chapter.

Chapter 2. Code generation architecture

The code generation mechanism in the Hibernate Tools consists of a few core concepts. This section explains their overall structure which are the same for the Ant and Eclipse tools.

2.1. Hibernate Meta Model

The meta model is the model used by Hibernate core to perform its object relational mapping. The model includes information about tables, columns, classes, properties, components, values, collections etc. The API is in org.hibernate.mapping and its main entry point is the Configuration class, the same class that is used to build a session factory.

The model represented by the Configuration class can be build in many ways. The best known is by using hbm.xml files to describe the meta model, other methods are using annotations in java source code and a third is reading JDBC metadata and build a configuration. The last method is provided via the reverse engineering part of the hibernate tools.

The code generation is done based on this model no matter which method have been used to create the meta model, and thus the code generation is independent on the source of the meta model and represented via Exporters.

2.2. Exporters

Code generation is done in so called Exporters. An Exporter is handed a Hibernate Meta Model represented as a Configuration instance and it is then the job of the exporter to generate a set of code artifacts.

The tools provides a default set of Exporter's which can be used in both Ant and the Eclipse UI. Documentation for these Exporters is in the Ant and Eclipse sections.

Users can provide their own customer Exporter's, either by custom classes implementing the Exporter interface or simply be providing custom templates. This is documented at Section 4.1.3.6, “Generic Hibernate metamodel exporter (<hbmtemplate>)”

NOTICE: This release uses Velocity for the templates. The next release might move to an alternative template engine.

Chapter 3. Eclipse Plugins

3.1. Introduction

 

The following features are available in the Hibernate Tools Eclipse plugins:

Mapping Editor: An editor for Hibernate XML mapping files, supporting auto-completion and syntax highlighting. It also supports semantic auto-completion for class names and property/field names, making it much more versatile than a normal XML editor.

Hibernate Console: The console is a new perspetive in Eclipse. It provides an overview of your Hibernate Console configurations, were also get an interactive view of your persistent classes and their relationships. The console allows you to execute HQL queries against your database and browse the result directly in Eclipse.

Configuration Wizards and Code generation: A set of wizards are provided with the Hibernate Eclipse tools; you can use a wizard to quickly generate common Hibernate configuration (cfg.xml) files, and from these you can code generate a series of various artifacts, there is even support for completely reverse engineer an existing database schema and use the code generation to generate POJO source files and Hibernate mapping files.

Please note that these tools do not try to hide any functionality of Hibernate. The tools make working with Hibernate easier, but you are still encouraged/required to read the documentation for Hibernate to fully utilize Hibernate Tools and especially Hibernate it self.

3.2. Creating a Hibernate configuration file

To be able to reverse engineer, prototype queries, and of course to simply use Hibernate a hibernate.properties or hibernate.cfg.xml file is needed. The Hibernate Tools provide a wizard for generating the hibernate.cfg.xml file if you do not already have such file.

Start the wizard by clicking "New Wizard" (Ctrl+N), select the Hibernate/Hibernate Configuration file (cfg.xml) wizard and press "Next". After selecting the wanted location for the hibernate.cfg.xml file, you will see the following page:

Tip: The contents in the combo boxes for the JDBC driver class and JDBC URL change automatically, depending on the Dialect and actual driver you have chosen.

Enter your configuration information in this dialog. Details about the configuration options can be found in Hibernate reference documentation.

Press "Finish" to create the configuration file, after optionally creating a Console onfiguration, the hibernate.cfg.xml will be automatically opened in an editor. The last option "Create Console Configuration" is enabled by default and when enabled i will automatically use the hibernate.cfg.xml for the basis of a "Console Configuration"

3.3. Creating a Hibernate Console configuration

A Console Configuration describes to the Hibernate plugin which configuration files should be used to configure hibernate, including which classpath is needed to load the POJO's, JDBC drivers etc. It is required to make usage of query prototyping, reverse engineering and code generation. You can have multiple named console configurations. Normally you would just need one per project, but more (or less) is definitly possible.

You create a console configuration by running the Console Configuration wizard, shown in the following screenshot. The same wizard will also be used if you are coming from the hibernate.cfg.xml wizard and had enabled "Create Console Configuration".

The following table describes the available settings. The wizard can automatically detect default values for most of these if you started the Wizard with the relevant java project selected

Table 3.1. Hibernate Console Configuration Parameters

Parameter

Description

Auto detected value

Name

The unique name of the configuration

Name of the selected project

Property file

Path to a hibernate.properties file

First hibernate.properties file found in the selected project

Configuration file

Path to a hibernate.cfg.xml file

First hibernate.cfg.xml file found in the selected project

Entity resolver

Fully qualified classname of a custom EntityResolver. Only required if you have special xml entity includes in your mapping files.

No default value

Enable Hibernate ejb3/annotations

Selecting this option enables usage of annotated classes. hbm.xml files are of course still possible to use too. This feature requires running the Eclipse IDE with a JDK 5 runtime, otherwise you will get classloading and/or version errors.

Not enabled

Mapping files

List of additional mapping files that should be loaded. Note: A hibernate.cfg.xml can also contain mappings. Thus if these a duplicated here, you will get "Duplicate mapping" errors when using the console configuration.

If no hibernate.cfg.xml file is found, all hbm.xml files found in the selected project

Classpath

The classpath for loading POJO and JDBC drivers. Do not add Hibernate core libraries or dependencies, they are already included. If you get ClassNotFound errors then check this list for possible missing or redundant directories/jars.

The default build output directory and any JARs with a class implementing java.sql.Driver in the selected project

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

3.4. Reverse engineering and code generation

A very simple "click-and-generate" reverse engineering and code generation facility is also available. This facility allows you to generate a range of artifacts based on database or an already existing Hibernate configuration, be that mapping files or annotations. Some of these are POJO Java source file, Hibernate *.hbm.xml, hibernate.cfg.xml generation and even the option for generating the skeleton for a full Seam CRUD application.

To start working with this process, start the "Hibernate Code Generation" which is available in the toolbar via the Hibernate icon or via the "Run/Hibernate Code Generation" menu item.

3.4.1. Code Generation Launcher

When you click on "Hibernate Code Generation" the standard Eclipse launcher dialog will appear. In this dialog you can create, edit and delete named Hibernate code generation "launchers".

The dialog has the standard tabs "Refresh" and "Common" that can be used to configure which directories should be automatically refreshed and various general settings launchers, such as saving them in a project for sharing the launcher within a team.

The first time you create a code generation launcher you should give it a meaningfull name, otherwise the default prefix "New_Generation" will be used.

Note: The "At least one exporter option must be selected" is just a warning stating that for this launch to work you need to select an exporter on the Exporter tab. When an exporter has been selected the warning will disappear.

On the "Main" tab you the following fields:

Table 3.2. Code generation "Main" tab fields

Field

Description

Console Configuration

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

Output directory

Path to a directory into where all output will be written by default. Be aware that existing files will be overwritten, so be sure to specify the correct directory.

Reverse engineer from JDBC Connection

If enabled the tools will reverse engineer the database available via the connection information in the selected Hibernate Console Configuration and generate code based on the database schema. If not enabled the code generation will just be based on the mappings already specified in the Hibernate Console configuration.

Package

The package name here is used as the default package name for any entities found when reverse engineering.

reveng.xml

Path to a reveng.xml file. A reveng.xml file allows you to control certain aspects of the reverse engineering. e.g. how jdbc types are mapped to hibernate types and especially important which tables are included/excluded from the process. Clicking "setup" allows you to select an existing reveng.xml file or create a new one. See more details about the reveng.xml file in Chapter 5, Controlling reverse engineering.

reveng. strategy

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

Generate basic typed composite ids

A table that has a multi-colum primary key a <composite-id> mapping will always be created. If this option is enabled and there are matching foreign-keys each key column is still considered a 'basic' scalar (string, long, etc.) instead of a reference to an entity. If you disable this option a <key-many-to-one> instead. Note: a <many-to-one> property is still created, but is simply marked as non-updatable and non-insertable.

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.

3.4.2. Exporters

The exporters tab is used to specify which type of code that should be generated. Each selection represents an "Exporter" that are responsible for generating the code, hence the name.

The following table describes in short the various exporters.

Table 3.3. Code generation "Exporter" tab fields

Field

Description

Generate domain code

Generates POJO's for all the persistent classes and components found in the given Hibernate configuration.

JDK 1.5 constructs

When enabled the POJO's will use JDK 1.5 constructs.

EJB3/JSR-220 annotations

When enabled the POJO's will be annotated according to the EJB3/JSR-220 persistency specification.

Generate DAO code

Generates a set of DAO's for each entity found.

Generate Mappings

Generate mapping (hbm.xml) files for each entity

Generate hibernate configuration file

Generate a hibernate.cfg.xml file. Used to keep the hibernate.cfg.xml uptodate with any new found mapping files.

Generate schema html-documentation

Generates set of html pages that documents the database schema and some of the mappings.

Generate JBoss Seam skeleton app (beta)

Generates a complete JBoss Seam skeleton app. The generation will include annotated POJO's, Seam controller beans and a JSP for the presentation layer. See the generated readme.txt for how to use it.

Note: this exporter generates a full application, including a build.xml thus you will get the best results if you use an output directory which is the root of your project.

3.5. Hibernate Mapping and Configuration File Editor

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 extend its functionallity to provide hiberante specific code completion.

3.5.1. Java property/class completion

Package, class, and field completion is enabled for relevant XML attributes. The auto-completion detects it's context and limits the completion for e.g. <property> and only shows the properties/fields available in the enclosing <class>, <subclass> etc. It is also possible to navigate from the hbm.xml files to the relevant class/field in java code.

This is done via the standard hyperlink navigation functionallity in Eclipse; per default it is done by pressing F3 while the cursor is on a class/field or by pressing Ctrl and the mouse button to perform the same navigation.

For java completion and navigation to work the file needs to reside inside an Eclipse Java project, otherwise no completion will occur. Note: java completion does not require a hibernate console configuration to be used.

3.5.2. Table/Column completion

Table and column completion is also available for all table and column attributes.

Note that it requires a proper configured hibernate console configuration and this configuration should be the default for the project where the hbm.xml resides.

You can check which console configuration is selected under the Properties of a project and look under the "Hibernate Settings" page. When a proper configuration is selected it will be used to fetch the table/column names in the background.

Note: Currently it is not recommended to use this feature on large databases since it does not fetch the information iteratively. It will be improved in future versions.

3.5.3. Configuration property completion

In cfg.xml code completion for the value of <property> name attributes is available.

3.6. Reveng.xml editor

A reveng.xml file is used to customize and control how reverse engineering is performed by the tools. The plugins provide and editor to ease the editing of this file and hence used to configure the reverse engineering process.

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

Note that not all the features of the .reveng.xml file is exposed or fully implemented in the editor, but the main functionallity is there. To understand the full flexibility of the reveng.xml, please see <xlink></xlink>

The editor is activated as soon as an .reveng.xml file is opened. To get an initial reveng.xml file the reveng.xml wizard can be started via Ctrl+N or via the code generation launcher.

The following screentshot shows the overview page where the wanted console configuration is selected (auto-detected if Hibernate 3 support is enabled for the project)

The table filter page allows you to specify which tables to include and exclude. Pressing refresh shows the tables from the database that have not yet been excluded.

Type mappings page is used for specifying type mappings from jdbc types to any hibernate type (including usertypes) if the default rules are not applicable.

Table Columns page allow the user to explicit set e.g. which hibernatetype and propertyname that should be used in the reverse engineered model.

3.7. Hibernate Console perspective

The Hibernate Console perspective combines a set of views which allow you to see the structure of your mapped entities/classes, edit HQL queries, execute the queries, and see the results. To use this perspective you need to create a console configuration.

3.7.1. Viewing the entity structure

To view your new configuration and entity/class structure, expand the Hibernate Console configuration by clicking on the + icon.

Clicking on the small + symbol allows you to browse the class/entity structure and see the relationships.

Hibernate Console perspective showing entity structure, query editor and result
3.7.1.1. Class Diagram

A class diagram is available in the view named "Hibernate Entity Model". It will show the model for any slected hibernate console configuration.

3.7.2. Prototyping Queries

Queries can be prototyped by entering them in the HQL editor. The HQL Editor is opened by right-clicking the Console configuration and select "HQL Scratchpad".

If the menu item is disabled then you need to first create an SessionFactory. That is done by right clicking the configuration and select "Create Session Factory" or by simpy expanding the Session Factory node.

Executing the query is done by clicking the green run button in the toolbar or pressing Ctrl+Enter.

Errors during creation of the SessionFactory or running the queries (e.g. if your configuration or query is incorrect) will be shown in a message dialog or inlined in the view that detected the error, you may get more information about the error in the Error Log view on the right pane.

Results of a query will be shown in the Query result view and details of possible errors (syntax errors, database errors, etc.) can be seen in the Error Log view.

Tip: HQL queries are executed using list() and without any limit of the size of the output. Be careful if you execute a query on a large result set. You might run out of memory. This will be improved in a future version.

3.7.2.1. Dynamic Query Translator

If the "Hibernate Dynamic Query Translator" view is visible while writing in the HQL editor it will show the generated SQL for a HQL query.

The translation is done each time you stop typing into the editor, if there are an error in the HQL the parse exception will be shown embedded in the view.

3.7.3. Properties view

The properties view shows the structure of any selected persistent object in the results view. Editing is not yet supported.

3.8. Enable debug logging in the plugins

It is possible to configure the eclipse plugin to route all logging made by the plugins and hibernate code it self to the "Error log" view in Eclipse.

This is done by editing the "hibernate-log4j.properties" in org.hibernate.eclipse/ directory/jar. This file includes a default configuration that only logs WARN and above to a set of custom appenders (PluginFileAppender and PluginLogAppender). You can change these settings to be as verbose or silent as you please - see hibernate documentation for interesting categories and log4j documentation for how to configure logging via a log4j property file.

Chapter 4. Ant Tools

4.1. Introduction

The hibernate-tools.jar contains the core for the Hibernate Tools. It is used as the basis for both the Ant tasks described in this document and the eclipse plugins both available from tools.hibernate.org The hibernate-tools.jar is located in your eclipse plugins directory at

/plugins/org.hibernate.eclipse.x.x.x/lib/tools/hibernate-tools.jar

. This jar is 100% independent from the eclipse platform.

4.1.1. The <hibernatetool> ant Task

To use the ant tasks you ned to have the hibernatetool task defined. That is done in your build.xml by inserting the following xml:

 <taskdef 
     name="hibernatetool" 
     classname="org.hibernate.tool.ant.HibernateToolTask" 
     classpath="[location of hibernate-tools.jar, velocity.jar, 
                 velocity-tools-generic.jar, jtidy.jar, 
                 hibernate3.jar & jdbc drivers]"/> 

This <taskdef> defines a 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 from http://annotations.hibernate.org. When using the <hibernatetool> task you have to specify one or more of the following:

<hibernatetool
  destdir="defaultDestinationDirectory"               (1)
  templatepath="defaultTemplatePath"                  (2)
>
  <classpath ...>                                     (3)
  <property name="propertyName" value="value"/>       (4)
  <propertyset ...>
  (<configuration ...>|<annotationconfiguration ...>|<jdbcconfiguration ...>)
  (<hbm2java>,<hbm2cfgxml>,...*)  
</hibernatetool>
(1)

destdir (requiredl): destination directory for files generated with exporters.

(2)

templatepath (optional): A path to be used to look up user-edited templates.

(3)

classpath (optional): A classpath to be used to resolve resources, such as mappings and usertypes. Optional, but very often required.

(4)

property and propertyset (optional): Used to set properties to control the exporters. Mostly relevant for providing custom properties to user defined templates.

4.1.2. Hibernate Configurations

hibernatetool supports three different Hibernate configurations: A standard Hibernate configuration (<configuration>), Annotation based configuration (<annotationconfiguratioin>) and a JDBC based configuration (<jdbcconfiguration>) for use when reverse engineering.

Each have in common that they are able to build up a Hibernate Configuration object from which a set of exporters can be run to generate various output.

4.1.2.1. Standard Hibernate Configuration (<configuration>)

A <configuration> is used to define a standard Hibernate configuration. A standard Hibernate configuration reads the mappings from the optional hbm.xml and the fileset.

<configuration
  configurationfile="hibernate.cfg.xml"               (1)
  propertyfile="hibernate.properties"                 (2)
  entityresolver="EntityResolver classname"           (3)
  namingstrategy="NamingStrategy classname"           (4)
>                                                     (5)
  <fileset...>
  
</configuration>
(1)

configurationfile (optional): The name of a Hibernate configuration file, e.g. "hibernate.cfg.xml"

(2)

propertyfile (optional): The name of a property file, e.g. "hibernate.properties"

(3)

entity-resolver (optional): name of a class that implements org.xml.sax.EntityResolver. Used if the mapping files require custom entity resolver.

(4)

namingstrategy (optional): name of a class that implements org.hibernate.cfg.NamingStrategy. Used for setting up the naming strategy in Hibernate which controls the automatic naming of tables and columns.

(5)

A standard Ant fileset. Used to include hibernate mapping files.Remember that if mappings are already specified in the hibernate.cfg.xml then it should not be included via the fileset as it will result in duplicate import exceptions.

4.1.2.2. Annotation based Configuration (<annotationconfiguration>)

An <annotationconfiguration> is used when you want to read the metamodel from EJB3/Hibernate Annotations based POJO's. To use it remember to put the jars file needed for using hibernate annotations in the classpath of the <taskdef>.

The <annotationconfiguration> has the same attributes as an <configuration> except that the configurationfile attribute is now required as that is from where an AnnotationConfiguration gets the list of classes/packages it should load.

Thus the minimal usage is:

<annotationconfiguration
  configurationfile="hibernate.cfg.xml"/>
4.1.2.3. JDBC Configuration for reverse engineering (<jdbcconfiguration>)

A <jdbcconfiguration> is used to perform reverse engineering of the database from a JDBC connection. The <jdbcconfiguration> has the same attributes as a <configuration> plus the following additional attributes:

<jdbcconfiguration
  ...
  packagename="package.name"
  reversestrategy="ReverseEngineeringStrategy classname"
  revengfile="hibernate.reveng.xml"
>
  ...
</jdbcconfiguration>

4.1.3. Code Exporters

Code exporters is the parts that does the actual job of converting the hibernate metamodel into various code artifacts. The following section describes the current supported set of exporters in the Hibernate Tool distribution. It is also possible for userdefined exporters, that is done through the <hbmtemplate> exporter.

4.1.3.1. Database schema exporter (<hbm2ddl>)

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

<hbm2ddl
 drop="true|false"
 create="true|false"
 export="true|false"
 update="true|false"
 outputfilename="filename.ddl"
 delimiter=";" 
 format="true|false"
>

 

4.1.3.2. POJO java code exporter (<hbm2java>)

<hbm2java> is a java codegenerator. Options for controlling wether JDK 5 syntax can be used and wether the POJO should be annotated with EJB3/Hibernate Annotations.

<hbm2java
 jdk5="true|false"
 ejb3="true|false"
>

 

4.1.3.3. Hibernate Mapping files exporter (<hbm2hbmxml>)

<hbm2hbmxml> generates a set of .hbm files. Intended to be used together with a <jdbcconfiguration> when performing reverse engineering, but can be used with any kind of configuration. e.g. to convert from annotation based pojo's to hbm.xml. Note that not every possible mapping transformation is possible/implemented so some hand editing might be necessary.

<hbm2hbmxml/>

 

4.1.3.4. Hibernate Configuration file exporter (<hbm2cfgxml>)

<hbm2cfgxml> generates a hibernate.cfg.xml. Intended to be used together with a <jdbcconfiguration> when performing reverse engineering, but can be used with any kind of configuration. The <hbm2cfgxml> will contain the properties used and adds mapping entriies for each mapped class.

<hbm2cfgxml
  ejb3="true|false"
/>

 

4.1.3.5. Documentation exporter (<hbm2doc>)

<hbm2doc> generates html documentation a'la javadoc for the database schema et.al.

<hbm2doc/>

 

4.1.3.6. Generic Hibernate metamodel exporter (<hbmtemplate>)

Generic exporter that can be controlled by a user provided template or class.

<hbmtemplate
 filepattern="{package-name}/{class-name}.vm"
 template="somename.vm"
 exporterclass="Exporter classname"
/>

NOTICE: This release uses Velocity for the templates. The next release might move to an alternative template engine.

4.1.3.6.1. Seam Exporter via <hbmtemplate>

The following is an example of reverse engineering via <jdbcconfiguration> and use the SeamExporter via the <hbmtemplate> to generate a Seam application skeleton.

 <hibernatetool destdir="${destdir}">
  <jdbcconfiguration configurationfile="hibernate.cfg.xml" packagename="x.y.z.seam.crud"/>   
  
  <!-- setup properties -->  
  <property key="seam_appname" value="Registration"/>
  <property key="seam_shortname" value="crud"/>
    
  <hbmtemplate exporterclass="org.hibernate.tool.hbm2x.seam.SeamExporter" filepattern="."/>
        
</hibernatetool>

4.1.4. Using properties to configure Exporters

Exporters can be controlled by user properties. The user properties is specificed via <property> or <propertyset> and each exporter will have access to them directly in the templates and via Exporter.setProperties().

 

4.1.4.1. <property> and <propertyset>

The <property> allows you bind a string value to a key. The value will be available in the templates via $<key>. The following example will assign the string value "true" to the variable $descriptors

<property key="descriptors" value="true"/>

Most times using <property> is enough for specifying the properties needed for the exporters. Still the ant tools supports the notion of <propertyset>. The functionallity of <propertyset> is explained in detail in the Ant task manual.

4.1.4.2. Getting access to user specific classes

If the templates need to access some user class it is possible by specifying a "toolclass" in the properties.

<property key="sometool.toolclass" value="x.y.z.NameOfToolClass"/>

Placing the above <property> tag in <hibernatetool> or inside any exporter will automatically create an instance of x.y.z.NameOfToolClass and it will be available in the templates as $sometool. This is usefull to delegate logic and code generation to java code instead of placing such logic in the templates.

 

Chapter 5. Controlling reverse engineering

When using the <jdbcconfiguration> the ant task will read the database metadata and from that perform a reverse engineering of the database schema into a normal Hibernate Configuration. It is from this object e.g. >hbm2java< can generate other artifacts such as .java, .hbm.xml etc.

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 foreignkeys into classes, properties and associations. It also used to provide mappings from SQL types to Hibernate types. The strategy can be customized by the user. The user can even provide its own custom reverse engineering strategy if the provided strategy is not enough, or simply just provide a small part of the strategy and delegate the rest to the default strategy.

5.1. Default reverse engineering strategy

The default strategy uses some rules for mapping JDBC artifact names to java artifact names. It also provide basic typemappings from JDBC types to Hibernate types. It is the default strategy that uses the packagename attribute to convert a table name to a fully qualified classname.

5.2. hibernate.reveng.xml file

To have fine control over the process a hibernate.reveng.xml file can be provided. In this file you can specify type mappings and table filtering. This file can be created by hand (its just basic XML) or you

can use the Hibernate plugins which have a specialized editor.

The following is an example of such a 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 fom 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 precisly -->
 <sql-type jdbc-type="NUMERIC"  precision='1' hibernate-type="boolean" /> 
 <!-- the type-mappings are ordered. This mapping will be consulted last, 
  thus overriden 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 
     are done for a specific table -->
<table name="ORDERS"> 
 <primary-key>
  <generator class="sequence">
    <param name="table">seq_table</param>
  </generator>
   <column name="CUSTID" foreign-table="CUSTOMER" foreign-column="CUSTID" />
 </primary-key>
 <column name="NAME" property="orderName" type="string" />
</table>

</hibernate-reverse-engineering>

 

5.2.1. Type mappings (<type-mapping>)

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"
 />
</type-mapping>

The number of attributes specificed and the sequence of the sql-type's is important. Meaning that 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.

5.2.1.1. Example

The following is an example of a type-mapping which shows the flexibility and the importance of 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:

Table 5.1. Supported meta tags

Column jdbc-type length precision not-null Resulting hibernate-type Rationale
ID INTEGER   10 true int Nothing defined for INTEGER. Falling back to default behavior.
NAME VARCHAR 30   false your.package.TrimStringUserType No type-mapping matches length=30 and not-null=false, but type-mapping matches the 2 mappings which only specifies VARCHAR. The type-mapping that comes first is chosen.
INITIAL VARCHAR 1   false char Even though there is a generic match for VARCHAR, the more specifc type-mapping for VARCHAR with not-null="false" is chosen. The first VARCHAR sql-type matches in length but has no value for not-null and thus is not considered.
CODE VARCHAR 1   true java.lang.Character The most specific VARCHAR with not-null="true" is selected.
SALARY NUMERIC   15 false big_decimal There is a precise match for NUMERIC with precision 15
AGE NUMERIC   3 false java.lang.Long type-mapping for NUMERIC with not-null="false"

 

5.2.2. Table filters (<table-filter>)

The <table-filter> let you specifcy matching rules for performing general filtering/setup for tables, e.g. let you include or exclude specific tables based on the schema or even a specifc prefix.

<table-filter
 match-catalog="catalog_matching_rule"
 match-schema="schema_matching_rule"
 match-name="table_matching_rule"
 exclude="true|false"
 package="package.name"
/>

5.2.3. Specific table configuration (<table>)

<table> allows you to provide explicit configuration on how a table should be reverse engineered. Amongst other things it allow control over the naming of a class for the table, specify which identifier generator should be used for the primary key etc.

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

 

<primary-key
 <generator class="generatorname">
   <param name="param_name">parameter value</param>
 </generator>
 <column...>
</primary-key>
5.2.3.2. <column>

 

<column
 name="column_name"
 jdbc-type="java.sql.Types type"
 type="hibernate_type"
 property="propertyName"
 exclude="true|false"
 foreign-catalog="catalogName"
 foreign-schema="schemaName"
 foreign-table="tableName"
 foreign-column="columnName"
/>
5.2.3.3. <foreign-key>

 

<foreign-key
  name="foreignKeyName"
  foreign-catalog="catalogName"
  foreign-schema="schemaName"
  foreign-table="tableName"
 >
 <column-ref local-column="columnName" foreign-column="foreignColumnName"/>
</foreign-key>

5.3. Custom strategy

It is possible to implement a user strategy. Such strategy must implement org.hibernate.cfg.reveng.ReverseEngineeringStrategy. It is recommended that one uses the DelegatingReverseEngineeringStrategy and provide a public constructor which takes another ReverseEngineeringStrategy as argument. This will allow you to only implement the relevant methods and provide a fallback strategy. Example of custom delegating strategy which converts all column names that ends with "PK" into a property named "id".

 

public class ExampleStrategy extends DelegatingReverseEngineeringStrategy {

 public ExampleStrategy(ReverseEngineeringStrategy delegate) {
  super(delegate);
 }

 public String columnToPropertyName(TableIdentifier table, String column) {
  if(column.endsWith("PK")) {
   return "id";
  } else {
   return super.columnToPropertyName(table, column);
  }
 }
}

Chapter 6. Controlling POJO code generation

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

6.1. The <meta> attribute

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

You can use the <meta> tag to e.g. tell hbm2java to only generate "protected" setters, have classes always implement a certain set of interfaces or even have them extend a certain base class and even 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 will produce something like the following (code shortened for better understanding). 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;
    }

}

Table 6.1. Supported meta tags

Attribute Description
class-description inserted into the javadoc for classes
field-description inserted into the javadoc for fields/properties
interface If true an interface is generated instead of an class.
implements interface the class should implement
extends class the class should extend (ignored for subclasses)
generated-class overrule the name of the actual class generated
scope-class scope for class
scope-set scope for setter method
scope-get scope for getter method
scope-field scope for actual field
default-value default initializatioin value for a field
use-in-tostring include this property in the toString()
use-in-equals include this property in the equals() and hashCode() method. If no use-in-equals is specificed, no equals/hashcode will be generated.
gen-property property will not be generated if false (use with care)
property-type Overrides the default type of property. Use this with any tag's to specify the concrete type instead of just Object.
class-code Extra code that will inserted at the end of the class
extra-import Extra import that will inserted at the end of all other imports

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

What does that mean? It means that if you e.g want to have all your classes implement IAuditable then you just add an <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 e.g. 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> at e.g. just under the <class> tag and all fields of that class will be protected.

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

 

转自:http://terryhello.spaces.live.com/blog/cns!D81BA124F0C3A224!117.entry

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值