1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Configuration configuration = new Configuration(); should load my existing hibernate.cfg.xml, which I have and there is line : <property name="hibernate.hbm2ddl.auto">create</property>
0

Yes. new Configuration() should load all the properties from hibernate.cfg.xml.

It seems that your SessionFactory is configured to be lazy initialized which only be built when HibernateUtil.getSessionFactory() is called.

If it is a console program , simple call SessionFactory.buildSessionFactory() in the main method

If it is a web application , you can use ServletContextListener.contextInitialized(ServletContextEvent sce) or Spring to force the SessionFactory.buildSessionFactory() to be executed during the server starts.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.