2012-09-28 18 views
1

我配置我的SessionFactory编程:使用Hibernate的编程配置,开始hibernate.hbm2ddl.auto

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); 
} 

但问题是,这些属性是使用休眠操作时才会加载,从道。

​​

因此,当我的应用程序启动时,则hibernate.hbm2ddl.auto似乎并​​没有工作。我可以以某种方式迫使hibernate.hbm2ddl.auto在我的程序或任何其他解决方案中启动?

推荐或其他选项,想法?

回答

3

您需要设置hibernate.hbm2ddl.auto或使用

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

使用配置文件中像hibernate.properties的hibernate.cfg.xml是设置您的设置更加首选方式。

+0

'配置配置=新配置();'应该加载我现有的hibernate.cfg.xml,我有和有行:' create' – Jaanus

0

是的。 new Configuration()应加载hibernate.cfg.xml的所有属性。

看起来您的SessionFactory被配置为延迟初始化,只有在调用HibernateUtil.getSessionFactory()时才会生成。

如果它是一个控制台程序,简单的调用SessionFactory.buildSessionFactory()的主要方法

如果它是一个Web应用程序,你可以使用ServletContextListener.contextInitialized(ServletContextEvent sce)或春天迫使SessionFactory.buildSessionFactory()在服务器启动过程中被执行。