Generate database schema DDL from Hibernate hbm mappings

Hibernate can be used to map Java classes to existing database tables. More often, the Java classes come first and the database is created around the mapping. If that’s the case, you’ll want to define your database schema directly from Hibernate mappings rather than hand crafting DDL scripts. Hibernate offers a couple of ways to do this.

hibernate.hbm2ddl.auto

The quickest way to create a database based on Hibernate mappings is to use the Hibernate hibernate.hbm2ddl.auto property. This can be set in the Hibernate configuration file (hibernate.cfg.xml) or in the Spring Hibernate Session Factory bean (LocalSessionFactoryBean) if you use Spring to configure as I do here.

Using the above settings, Hibernate will create the database schema on application start up. This is great to get started quickly but no use for a production environment. On application start up, the database schema is cleared down and recreated – all existing data will be lost.

A quick hack is to use the create setting during development and then use your favourite database tool to export the schema DDL from the database. For a production build, this setting must be changed back to validate or removed. The resulting DDL can be used to initialize any other environment before first run. The application can then be started and stopped without fear of dropping the schema and data.

This is a little bit of a hack and not really advisable for anything other than hobby projects.

hibernate3-maven-plugin

The hibernate3-maven-plugin can also be used to create a schema DDL from Hibernate mapping files. This is a more robust way of creating DDL files as it can be built into the Maven build process and controlled with profiles if necessary. The following Maven profile allows optional generation of a schema DDL file:

The schema can be created by activating the hbm2ddl profile like so

The resulting DDL file will be specific to your chosen database vendor as the database dialect is defined in the file specified by the propertyfile property (hibernate-mysql.properties):


The hibernate.cfg.xml used here simply lists the mapping files to scan:

The resulting DDL script contains all information that can be inferred from the hibernate mapping including column types and widths, foreign keys and constraints.

Leave a Reply

Your email address will not be published. Required fields are marked *