M. Assassa
M. Assassa

Reputation: 151

Programmatic SchemaUpdate in Hibernate 4

I'm trying to run a SchemaUpdate in my Java EE 6 application. In previous Hibernate versions I managed to do so creating an Ejb3Configuration and then running a SchemaUpdate. Pretty much like this:

Ejb3Configuration cfg = new Ejb3Configuration();
cfg.configure(PERSISTENCE_UNIT_NAME, null);
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
cfg.setProperty("hibernate.dialect", dialect.getClass().getName());
Collection<String> entityClassNames = getEntityClassNames(PERSISTENCE_UNIT_NAME);
for (String className : entityClassNames)
{
    cfg.addAnnotatedClass(Class.forName(className));
}

EntityManagerFactory factory =  Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

new SchemaUpdate(cfg.getHibernateConfiguration()).execute(true, true);

Apparently the class Ejb3Config is deprecated and is not supported. So what is the proper way to do a SchemaUpdate with hibernate 4?

Upvotes: 2

Views: 1006

Answers (1)

Tom Anderson
Tom Anderson

Reputation: 47163

You say you're using EE 6. Are you therefore using a persistence.xml and all the standard JPA stuff? If not, then that's a mistake, and the first step is to go back and fix that. Using a persistence.xml, you can specify schema update on startup with a property:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

    <persistence-unit name="...">
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>

</persistence>

Would that be suitable? Or do you have a partcular reason for doing this manually?

Upvotes: 1

Related Questions