Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top