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>

Create own ID column auto managed by JPA

By default, JPA uses Id column, but I want to create my own id column named userid for my user table. I am always confused with Id column in multiple tables so I append entity name before id in order to know which one I am referring. For an example, for user table I use userid, for customer, I use customerid and so on.

For that, I created a new id column for JPA entity and annotated it with @Id.

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "user_id")
 private Integer userid;


But it didn't work for me. After searching the web for some time, I found out that I should use full package name for ID. in the place of @Id, I had to use @javax.persistence.Id The resulting code was this

 @javax.persistence.Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "user_id")
 private Integer userid;

Now the code works fine.