Jason Miesionczek Jason Miesionczek - 2 years ago 95
Java Question

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

I have the following entity class (in Groovy):

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

public class ServerNode {

@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">
<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"/>

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.persist new ServerNode(firstName: "Test", lastName: "Server")


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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download