Hibernate using Programmatic Configuration, starting hibernate.hbm2ddl.auto

Jaanus picture Jaanus · Sep 28, 2012 · Viewed 12.3k times · Source

I am configuration my hibernate sessionfactory programmatically:

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html#configuration-programmatic

private static SessionFactory buildSessionFactory() {

        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure();

        configuration.setProperty("hibernate.connection.url", myUrl);
        configuration.setProperty("hibernate.connection.username", myUser);
        configuration.setProperty("hibernate.connection.password", myPass);

        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 

        return configuration.buildSessionFactory(serviceRegistry);
}

But problem, is that these properties are loaded only, when using hibernate operation from dao.

protected void startOperation() {
    session = HibernateUtil.getSessionFactory().openSession();
    tx = session.beginTransaction();
}

Therefore, when my application boots up, then hibernate.hbm2ddl.auto doesn't seem to work. Can I somehow force hibernate.hbm2ddl.auto to start in my program or any other solution?

Suggetions or other options, thoughts?

Answer

swemon picture swemon · Sep 28, 2012

You need to set hibernate.hbm2ddl.auto or used

configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");

Using configuration file like hibernate.properties or hibernate.cfg.xml is more preferred way to set your setting.