Monday, July 25, 2016

Hibernate's hbm2ddl Tool

The Hibernate hbm2ddl is a tool allows us to create, update, and validate a database schema using Hibernate mappings configuration. The .hbm files are Hibernate mapping files, but since the schema export/validation is done using the the internal configuration Hibernate creates for the entities mapping, we can use still use hbm2ddl when working with JPA. As usual in here I write about the JPA environment, just remember that the hbm2ddl can also be invoked from command line or using Ant task.

Setup
To invoke Hibernates hbm2ddl during the creation of the entity manager factory set the 'hibernate.hbm2ddl.auto' property to one of 
·         create
·         create-drop
·         update
·         validate
Here is an example:
<persistence>
  <persistence-unit name="sampleContext" transaction-type="RESOURCE_LOCAL">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <properties>
    <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver">
     <property name="hibernate.connection.username" value="app">
     <property name="hibernate.connection.password" value="app">
     <property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/HibernateTestDB;create=true">
     <property name="hibernate.hbm2ddl.auto" value="validate">
   </properties>
   </persistence-unit>
</persistence>

The Options and Their Meanings

create

Hibernate will create the database when the entity manager factory is created (actually when Hibernate's SessionFactory is created by the entity manager factory). If a file named import.sql exists in the root of the class path ('/import.sql') Hibernate will execute the SQL statements read from the file after the creation of the database schema. It is important to remember that before Hibernate creates the schema it empties it (delete all tables, constraints, or any other database object that is going to be created in the process of building the schema).

create-drop

Same as 'create' but when the entity manager factory (which holds the SessionFactory) is explicitly closed the schema will be dropped.

update

Hibernate creates an update script trying to update the database structure to the current mapping. Does not read and invoke the SQL statements from import.sql. Useful, but we have to be careful, not all of the updates can be done performed ? for example adding a not null column to a table with existing data.

validate

Validates the existing schema with the current entities configuration. When using this mode Hibernate will not do any changes to the schema and will not use the import.sql file.

Mode
Reads
import.sql
Alters Database
Structure
Comments
update
No
Yes

create
Yes
Yes
Empties the database before creating it
create-drop
Yes
Yes
Drops the database when the SessionFactory is closed
validate
No
No

No comments:

Post a Comment