java 使用编程配置休眠,启动 hibernate.hbm2ddl.auto
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12636015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate using Programmatic Configuration, starting hibernate.hbm2ddl.auto
提问by Jaanus
I am configuration my hibernate sessionfactory programmatically:
我正在以编程方式配置我的休眠 sessionfactory:
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.
但问题是,这些属性仅在使用 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?
因此,当我的应用程序启动时,hibernate.hbm2ddl.auto 似乎不起作用。我可以以某种方式强制 hibernate.hbm2ddl.auto 在我的程序或任何其他解决方案中启动吗?
Suggetions or other options, thoughts?
建议或其他选择、想法?
回答by swemon
You need to set hibernate.hbm2ddl.auto or used
您需要设置 hibernate.hbm2ddl.auto 或 used
configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
Using configuration file like hibernate.propertiesor hibernate.cfg.xmlis more preferred way to set your setting.
使用hibernate.properties或hibernate.cfg.xml 之类的配置文件是设置设置的首选方式。
回答by Ken Chan
Yes. new Configuration()
should load all the properties from hibernate.cfg.xml
.
是的。new Configuration()
应该从hibernate.cfg.xml
.
It seems that your SessionFactory
is configured to be lazy initialized which only be built when HibernateUtil.getSessionFactory()
is called.
似乎您 SessionFactory
配置为延迟初始化,仅在HibernateUtil.getSessionFactory()
调用时构建 。
If it is a console program , simple call SessionFactory.buildSessionFactory()
in the main method
如果是控制台程序,SessionFactory.buildSessionFactory()
在main方法中简单调用
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.
如果是web应用,可以使用ServletContextListener.contextInitialized(ServletContextEvent sce)或者Spring强制SessionFactory.buildSessionFactory()
在服务器启动时执行。