Thursday, May 22, 2014

Hibernate Table Deleted After Stopping and Starting New Session in Java Application

When I was new to Hibernate and JPA, I used Hibernate to create table from Entity definition. But I was annoyed to find out it was always deleted after the program was closed and started again. But the solution was very simple. I had to open the persistence.xml file and edit some valued. When I opened the persistence.xml file the file contents was like following: The persistence.xml file is generally located inside src/main/resources/META-INF/ folder.
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect">
      <property name="hibernate.hbm2ddl.auto" value="create">
      <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy">
      <property name="hibernate.connection.charSet" value="UTF-8">
   </property></property></property></property></properties>
</persistence-unit>

I had to edit the property
<property name="hibernate.hbm2ddl.auto" value="create"></property>

The community documentation states that hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
There are few options for this property and they are: validate | update | create | create-drop

  • validate: validates the schema, it makes no changes to the database. 
  • update: update the schema. 
  • create: creates the schema, it destroys the current data before creating the new table, but does not destroy after the end of the session. 
  • create-drop: drop the schema at the end of the session and create it at the beginning of session.

So I changed the value to update and the value in database remained intact in new sessions.
<property name="hibernate.hbm2ddl.auto" value="update"></property>

No comments:

Post a Comment