Hibernate: Automatically creating/updating the db tables based on entity classes

JavaMysqlHibernateJpaGroovy

Java Problem Overview


I have the following entity class (in Groovy):

import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType

@Entity
public class ServerNode {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id

  String firstName
  String lastName

}

and my persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="NewPersistenceUnit">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/Icarus"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hbm2ddl.auto" value="create"/>
        </properties>
        <class>net.interaxia.icarus.data.models.ServerNode</class>
    </persistence-unit>
</persistence>

and the script:

import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence
import net.interaxia.icarus.data.models.ServerNode

def factory = Persistence.createEntityManagerFactory("NewPersistenceUnit")
def manager = factory.createEntityManager()

manager.getTransaction().begin()

manager.persist new ServerNode(firstName: "Test", lastName: "Server")

manager.getTransaction().commit()

the database Icarus exists, but currently has no tables. I would like Hibernate to automatically create and/or update the tables based on the entity classes. How would I accomplish this?

Java Solutions


Solution 1 - Java

I don't know if leaving hibernate off the front makes a difference.

The reference suggests it should be hibernate.hbm2ddl.auto

A value of create will create your tables at sessionFactory creation, and leave them intact.

A value of create-drop will create your tables, and then drop them when you close the sessionFactory.

Perhaps you should set the javax.persistence.Table annotation explicitly?

Hope this helps.

Solution 2 - Java

You might try changing this line in your persistence.xml from

<property name="hbm2ddl.auto" value="create"/>

to:

<property name="hibernate.hbm2ddl.auto" value="update"/>

This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.

Got this from JavaRanch

Solution 3 - Java

Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.

e.g. if you have it like:

<property name="hibernate.hbm2ddl.auto" value="create"/>

try changing it to:

<property name="hibernate.hbm2ddl.auto">create</property>

Solution 4 - Java

In my case table was not created for the first time without last property listed below:

<properties>
    <property name="hibernate.archive.autodetection" value="class"/>
    <property name="hibernate.show_sql" value="true"/>
    <property name="hibernate.format_sql" value="true"/>
    <property name="hbm2ddl.auto" value="create-drop"/>
    <!-- without below table was not created -->
    <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
</properties>

used Wildfly's in-memory H2 database

Solution 5 - Java

There is one very important detail, than can possibly stop your hibernate from generating tables (assuming You already have set the hibernate.hbm2ddl.auto). You will also need the @Table annotation!

@Entity
@Table(name = "test_entity")
    public class TestEntity {
}

It has already helped in my case at least 3 times - still cannot remember it ;)

PS. Read the hibernate docs - in most cases You will probably not want to set hibernate.hbm2ddl.auto to create-drop, because it deletes Your tables after stopping the app.

Solution 6 - Java

In applicationContext.xml file:

<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.howtodoinjava.demo.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
      	   Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
   </bean>

Solution 7 - Java

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

Solution 8 - Java

  1. TO CREATING TABLE AUTOMATIC , NO CONNECTION WITH ANNOTATIONS
  2. FOR THAT WE NEED TO CHANGE "hibernate.cfg.xml" as like.
 <property name="hbm2ddl.auto">update</property>  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason MiesionczekView Question on Stackoverflow
Solution 1 - JavatoolkitView Answer on Stackoverflow
Solution 2 - JavabilljamesdevView Answer on Stackoverflow
Solution 3 - JavaHarbirView Answer on Stackoverflow
Solution 4 - JavaDevDioView Answer on Stackoverflow
Solution 5 - JavathorinkorView Answer on Stackoverflow
Solution 6 - JavaYusuf AksunView Answer on Stackoverflow
Solution 7 - JavaAbsoluteDevView Answer on Stackoverflow
Solution 8 - JavaRizwan AliView Answer on Stackoverflow