Este contenido no está disponible en el idioma seleccionado.

20.2. Automatic Schema Generation


20.2.1. Customizing the Schema

Many Hibernate mapping elements define optional attributes named length, precision and scale. You can set the length, precision and scale of a column with this attribute.
<property name="zip" length="5"/>
Copy to Clipboard Toggle word wrap
<property name="balance" precision="12" scale="2"/>
Copy to Clipboard Toggle word wrap
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.
<many-to-one name="bar" column="barId" not-null="true"/>
Copy to Clipboard Toggle word wrap
<element column="serialNumber" type="long" not-null="true" unique="true"/>
Copy to Clipboard Toggle word wrap
A unique-key attribute can be used to group columns in a single, unique key constraint. Currently, the specified value of the unique-key attribute is not 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"/>
Copy to Clipboard Toggle word wrap
An index 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"/>
Copy to Clipboard Toggle word wrap
A foreign-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"/>
Copy to Clipboard Toggle word wrap
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>
Copy to Clipboard Toggle word wrap
The default 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>
Copy to Clipboard Toggle word wrap
<version name="version" type="integer" insert="false">
    <column name="version" default="0"/>
</property>
Copy to Clipboard Toggle word wrap
The sql-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>
Copy to Clipboard Toggle word wrap
The check attribute allows you to specify a check constraint.
<property name="foo" type="integer">
    <column name="foo" check="foo > 10"/>
</property>
Copy to Clipboard Toggle word wrap
<class name="Foo" table="foos" check="bar < 100.0">
    ...
    <property name="bar" type="float"/>
</class>
Copy to Clipboard Toggle word wrap
The following table summarizes these optional attributes.
Expand
Table 20.1. Summary
Attribute Values Interpretation
length number column length
precision number column decimal precision
scale number column decimal scale
not-null true|false specifies that the column should be non-nullable
unique true|false specifies that the column should have a unique constraint
index index_name specifies the name of a (multi-column) index
unique-key unique_key_name specifies the name of a multi-column unique constraint
foreign-key foreign_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 that inverse="true" sides will not be considered by SchemaExport.
sql-type SQL column type overrides the default column type (attribute of <column> element only)
default SQL expression specify a default value for the column
check SQL 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>
Copy to Clipboard Toggle word wrap
<property name="balance">
    <column name="bal">
        <comment>Balance in USD</comment>
    </column>
</property>
Copy to Clipboard Toggle word wrap
This results in a comment on table or comment on column statement in the generated DDL where supported.

20.2.2. Running the Tool

The SchemaExport tool writes a DDL script to standard out and/or executes the DDL statements.
The following table displays the SchemaExport command line options
java -cphibernate_classpathsorg.hibernate.tool.hbm2ddl.SchemaExport options mapping_files
Expand
Table 20.2. SchemaExport Command Line Options
Option Description
--quiet do not output the script to stdout
--drop only drop the tables
--create only create the tables
--text do not export to the database
--output=my_schema.ddl output the ddl script to a file
--naming=eg.MyNamingStrategy select a NamingStrategy
--config=hibernate.cfg.xml read Hibernate configuration from an XML file
--properties=hibernate.properties read database properties from a file
--format format the generated SQL nicely in the script
--delimiter=; set an end of line delimiter for the script
You can even embed SchemaExport in your application:
Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);
Copy to Clipboard Toggle word wrap

20.2.3. Database Properties

Database properties can be specified:
  • as system properties with -D<property>
  • in hibernate.properties
  • in a named properties file with --properties
The needed properties are:
Expand
Table 20.3. SchemaExport Connection Properties
Property Name Description
hibernate.connection.driver_class jdbc driver class
hibernate.connection.url jdbc url
hibernate.connection.username database user
hibernate.connection.password user password
hibernate.dialect dialect

20.2.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>
Copy to Clipboard Toggle word wrap

20.2.5. Incremental Schema Updates

The SchemaUpdate tool will update an existing schema with "incremental" changes. The SchemaUpdate depends upon the JDBC metadata API and, as such, will not work with all JDBC drivers.
java -cphibernate_classpathsorg.hibernate.tool.hbm2ddl.SchemaUpdate options mapping_files
Expand
Table 20.4. SchemaUpdate Command Line Options
Option Description
--quiet do not output the script to stdout
--text do not export the script to the database
--naming=eg.MyNamingStrategy select a NamingStrategy
--properties=hibernate.properties read database properties from a file
--config=hibernate.cfg.xml specify a .cfg.xml file
You can embed SchemaUpdate in your application:
Configuration cfg = ....;
new SchemaUpdate(cfg).execute(false);
Copy to Clipboard Toggle word wrap

20.2.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>
Copy to Clipboard Toggle word wrap

20.2.7. Schema Validation

The SchemaValidator tool will validate that the existing database schema "matches" your mapping documents. The SchemaValidator 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.SchemaValidator options mapping_files
The following table displays the SchemaValidator command line options:
Expand
Table 20.5. SchemaValidator Command Line Options
Option Description
--naming=eg.MyNamingStrategy select a NamingStrategy
--properties=hibernate.properties read database properties from a file
--config=hibernate.cfg.xml specify a .cfg.xml file
You can embed SchemaValidator in your application:
Configuration cfg = ....;
new SchemaValidator(cfg).validate();
Copy to Clipboard Toggle word wrap

20.2.8. Using Ant for Schema Validation

You can call SchemaValidator 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>
Copy to Clipboard Toggle word wrap
Volver arriba
Red Hat logoGithubredditYoutubeTwitter

Aprender

Pruebe, compre y venda

Comunidades

Acerca de la documentación de Red Hat

Ayudamos a los usuarios de Red Hat a innovar y alcanzar sus objetivos con nuestros productos y servicios con contenido en el que pueden confiar. Explore nuestras recientes actualizaciones.

Hacer que el código abierto sea más inclusivo

Red Hat se compromete a reemplazar el lenguaje problemático en nuestro código, documentación y propiedades web. Para más detalles, consulte el Blog de Red Hat.

Acerca de Red Hat

Ofrecemos soluciones reforzadas que facilitan a las empresas trabajar en plataformas y entornos, desde el centro de datos central hasta el perímetro de la red.

Theme

© 2025 Red Hat