Movatterモバイル変換


[0]ホーム

URL:


Hibernate.orgCommunity Documentation

Chapter 21. Toolset Guide

Table of Contents

21.1. Automatic schema generation
21.1.1. Customizing the schema
21.1.2. Running the tool
21.1.3. Properties
21.1.4. Using Ant
21.1.5. Incremental schema updates
21.1.6. Using Ant for incremental schema updates
21.1.7. Schema validation
21.1.8. Using Ant for schema validation

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

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

Please refer to theHibernate Tools package documentation for more information.

However, the Hibernate main package comes bundled with an integrated tool :SchemaExport akahbm2ddl.It can even be used from "inside" Hibernate.

21.1. Automatic schema generation

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

Youmust specify a SQLDialect via thehibernate.dialect property when using this tool, as DDL is highly vendor-specific.

First, you must customize your mapping files to improve the generated schema. The next section covers schema customization.

Many Hibernate mapping elements define optional attributes namedlength,precision andscale. You can set the length, precision and scale of a column with this attribute.

<property name="zip" length="5"/>
<property name="balance" precision="12" scale="2"/>

Some tags also accept anot-null attribute for generating aNOT NULL constraint on table columns, and aunique attribute for generatingUNIQUE constraint on table columns.

<many-to-one name="bar" column="barId" not-null="true"/>
<element column="serialNumber" type="long" not-null="true" unique="true"/>

Aunique-key attribute can be used to group columns in a single, unique key constraint. Currently, the specified value of theunique-key attribute isnot used to name the constraint in the generated DDL. It is only used to group the columns in the mapping file.

<many-to-one name="org" column="orgId" unique-key="OrgEmployeeId"/><property name="employeeId" unique-key="OrgEmployee"/>

Anindex attribute specifies the name of an index that will be created using the mapped column or columns. Multiple columns can be grouped into the same index by simply specifying the same index name.

<property name="lastName" index="CustName"/><property name="firstName" index="CustName"/>

Aforeign-key attribute can be used to override the name of any generated foreign key constraint.

<many-to-one name="bar" column="barId" foreign-key="FKFooBar"/>

Many mapping elements also accept a child<column> element. This is particularly useful for mapping multi-column types:

<property name="name" type="my.customtypes.Name"/>    <column name="last" not-null="true" index="bar_idx" length="30"/>    <column name="first" not-null="true" index="bar_idx" length="20"/>    <column name="initial"/></property>

Thedefault attribute allows you to specify a default value for a column.You should assign the same value to the mapped property before saving a new instance of the mapped class.

<property name="credits" type="integer" insert="false">    <column name="credits" default="10"/></property>
<version name="version" type="integer" insert="false">    <column name="version" default="0"/></property>

Thesql-type attribute allows the user to override the default mapping of a Hibernate type to SQL datatype.

<property name="balance" type="float">    <column name="balance" sql-type="decimal(13,3)"/></property>

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

The following table summarizes these optional attributes.

Table 21.1. Summary

AttributeValuesInterpretation
lengthnumbercolumn length
precisionnumbercolumn decimal precision
scalenumbercolumn decimal scale
not-nulltrue|falsespecifies 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, for a<one-to-one>,<many-to-one>,<key>, or<many-to-many> mapping element. Note thatinverse="true" sides will not be considered bySchemaExport.
sql-typeSQL column type overrides the default column type (attribute of<column> element only)
defaultSQL expression specify a default value for the column
checkSQL expression create an SQL check constraint on either column or table

The<comment> element allows you to specify 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 acomment on table orcomment on column statement in the generated DDL where supported.

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

The following table displays theSchemaExport command line options

java -cphibernate_classpathsorg.hibernate.tool.hbm2ddl.SchemaExportoptions mapping_files

Table 21.2. SchemaExport Command Line Options

OptionDescription
--quietdo not output the script to stdout
--droponly drop the tables
--createonly create the tables
--textdo not export to the database
--output=my_schema.ddloutput the ddl script to a file
--naming=eg.MyNamingStrategyselect aNamingStrategy
--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=;set an end of line delimiter for the script

You can even embedSchemaExport in your application:

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

Database properties can be specified:

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

You can callSchemaExport 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>

TheSchemaUpdate tool will update an existing schema with "incremental" changes. TheSchemaUpdate depends upon the JDBC metadata API and, as such, will not work with all JDBC drivers.

java -cphibernate_classpathsorg.hibernate.tool.hbm2ddl.SchemaUpdateoptions mapping_files

Table 21.4. SchemaUpdate Command Line Options

OptionDescription
--quietdo not output the script to stdout
--textdo not export the script to the database
--naming=eg.MyNamingStrategyselect aNamingStrategy
--properties=hibernate.propertiesread database properties from a file
--config=hibernate.cfg.xmlspecify a.cfg.xml file

You can embedSchemaUpdate in your application:

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

You can callSchemaUpdate 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>

TheSchemaValidator tool will validate that the existing database schema "matches" your mapping documents. TheSchemaValidator depends heavily upon the JDBC metadata API and, as such, will not work with all JDBC drivers. This tool is extremely useful for testing.

java -cphibernate_classpathsorg.hibernate.tool.hbm2ddl.SchemaValidatoroptions mapping_files

The following table displays theSchemaValidator command line options:

Table 21.5. SchemaValidator Command Line Options

OptionDescription
--naming=eg.MyNamingStrategyselect aNamingStrategy
--properties=hibernate.propertiesread database properties from a file
--config=hibernate.cfg.xmlspecify a.cfg.xml file

You can embedSchemaValidator in your application:

Configuration cfg = ....;new SchemaValidator(cfg).validate();

You can callSchemaValidator from the Ant script:

<target name="schemavalidate">    <taskdef name="schemavalidator"        classname="org.hibernate.tool.hbm2ddl.SchemaValidatorTask"        classpathref="class.path"/>        <schemavalidator        properties="hibernate.properties">        <fileset dir="src">            <include name="**/*.hbm.xml"/>        </fileset>    </schemavalidator></target>


[8]ページ先頭

©2009-2025 Movatter.jp