Chapter 21. Toolset Guide

Roundtrip engineering with Hibernate is possible using a set of Eclipse plugins, commandline tools, as well as Ant tasks.

The Hibernate Tools currently include plugins for the Eclipse IDE as well as Ant tasks for reverse engineering of existing databases:

Please refer to the Hibernate Tools package and it's documentation for more information.

However, the Hibernate main package comes bundled with an integrated tool (it can even be used from "inside" Hibernate on-the-fly): SchemaExport aka hbm2ddl.

21.1. Automatic schema generation

DDL may be generated from your mapping files by a Hibernate utility. The generated schema includes referential integrity constraints (primary and foreign keys) for entity and collection tables. Tables and sequences are also created for mapped identifier generators.

You must specify a SQL Dialect via the hibernate.dialect property when using this tool, as DDL is highly vendor specific.

First, customize your mapping files to improve the generated schema.

21.1.1. Customizing the schema

Many Hibernate mapping elements define an optional attribute named length. You may set the length of a column with this attribute. (Or, for numeric/decimal data types, the precision.)

Some tags also accept a not-null attribute (for generating a NOT NULL constraint on table columns) and a unique attribute (for generating UNIQUE constraint on table columns).

Some tags accept an index attribute for specifying the name of an index for that column. A unique-key attribute can be used to group columns in a single unit key constraint. Currently, the specified value of the unique-key attribute is not used to name the constraint, only to group the columns in the mapping file.

Examples:

<property name="foo" type="string" length="64" not-null="true"/>

<many-to-one name="bar" foreign-key="fk_foo_bar" not-null="true"/>

<element column="serial_number" type="long" not-null="true" unique="true"/>

Alternatively, these elements also accept a child <column> element. This is particularly useful for multi-column types:

<property name="foo" type="string">
    <column name="foo" length="64" not-null="true" sql-type="text"/>
</property>
<property name="bar" type="my.customtypes.MultiColumnType"/>
    <column name="fee" not-null="true" index="bar_idx"/>
    <column name="fi" not-null="true" index="bar_idx"/>
    <column name="fo" not-null="true" index="bar_idx"/>
</property>

The sql-type attribute allows the user to override the default mapping of Hibernate type to SQL datatype.

The check attribute allows you to specify a check constraint.

<property name="foo" type="integer">
    <column name="foo" check="foo > 10"/>
</property>
<class name="Foo" table="foos" check="bar < 100.0">
    ...
    <property name="bar" type="float"/>
</class>

Table 21.1. Summary

AttributeValuesInterpretation
lengthnumbercolumn length/decimal precision
not-nulltrue|falsespecfies that the column should be non-nullable
uniquetrue|falsespecifies that the column should have a unique constraint
indexindex_namespecifies the name of a (multi-column) index
unique-keyunique_key_namespecifies the name of a multi-column unique constraint
foreign-keyforeign_key_name specifies the name of the foreign key constraint generated for an association, use it on <one-to-one>, <many-to-one>, <key>, and <many-to-many> mapping elements. Note that inverse="true" sides will not be considered by SchemaExport.
sql-typecolumn_type overrides the default column type (attribute of <column> element only)
checkSQL expression create an SQL check constraint on either column or table

The <comment> element allows you to specify a comments for the generated schema.

<class name="Customer" table="CurCust">
    <comment>Current customers only</comment>
    ...
</class>
<property name="balance">
    <column name="bal">
        <comment>Balance in USD</comment>
    </column>
</property>

This results in a comment on table or comment on column statement in the generated DDL (where supported).

21.1.2. Running the tool

The SchemaExport tool writes a DDL script to standard out and/or executes the DDL statements.

java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files

Table 21.2. SchemaExport Command Line Options

OptionDescription
--quietdon't output the script to stdout
--droponly drop the tables
--textdon't export to the database
--output=my_schema.ddloutput the ddl script to a file
--config=hibernate.cfg.xmlread Hibernate configuration from an XML file
--properties=hibernate.propertiesread database properties from a file
--formatformat the generated SQL nicely in the script
--delimiter=xset an end of line delimiter for the script

You may even embed SchemaExport in your application:

Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);

21.1.3. Properties

Database properties may be specified

  • as system properties with -D<property>

  • in hibernate.properties

  • in a named properties file with --properties

The needed properties are:

Table 21.3. SchemaExport Connection Properties

Property NameDescription
hibernate.connection.driver_classjdbc driver class
hibernate.connection.urljdbc url
hibernate.connection.usernamedatabase user
hibernate.connection.passworduser password
hibernate.dialectdialect

21.1.4. Using Ant

You can call SchemaExport from your Ant build script:

<target name="schemaexport">
    <taskdef name="schemaexport"
        classname="org.hibernate.tool.hbm2ddl.SchemaExportTask"
        classpathref="class.path"/>
    
    <schemaexport
        properties="hibernate.properties"
        quiet="no"
        text="no"
        drop="no"
        delimiter=";"
        output="schema-export.sql">
        <fileset dir="src">
            <include name="**/*.hbm.xml"/>
        </fileset>
    </schemaexport>
</target>

21.1.5. Incremental schema updates

The SchemaUpdate tool will update an existing schema with "incremental" changes. Note that SchemaUpdate depends heavily upon the JDBC metadata API, so it will not work with all JDBC drivers.

java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaUpdate options mapping_files

Table 21.4. SchemaUpdate Command Line Options

OptionDescription
--quietdon't output the script to stdout
--properties=hibernate.propertiesread database properties from a file

You may embed SchemaUpdate in your application:

Configuration cfg = ....;
new SchemaUpdate(cfg).execute(false);

21.1.6. Using Ant for incremental schema updates

You can call SchemaUpdate from the Ant script:

<target name="schemaupdate">
    <taskdef name="schemaupdate"
        classname="org.hibernate.tool.hbm2ddl.SchemaUpdateTask"
        classpathref="class.path"/>
    
    <schemaupdate
        properties="hibernate.properties"
        quiet="no">
        <fileset dir="src">
            <include name="**/*.hbm.xml"/>
        </fileset>
    </schemaupdate>
</target>