java 运行时的休眠配置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1341871/
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 configuration on runtime
提问by Oleksandr
I have hibernate.cfg.xml file.
我有 hibernate.cfg.xml 文件。
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url"></property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
.....................
………………
This is the most interesting part of file. Now i must set missing values: url, username, password. I'm trying to do in such way:
这是文件中最有趣的部分。现在我必须设置缺失值:url、用户名、密码。我正在尝试这样做:
public static void SetSessionFactory() {
try {
AnnotationConfiguration conf = new AnnotationConfiguration().configure();
// <!-- Database connection settings -->
conf.setProperty("connection.url", URL);
conf.setProperty("connection.username", USERNAME);
conf.setProperty("connection.password", PASSWORD);
SESSION_FACTORY = conf.buildSessionFactory();
} catch (Throwable ex) {
// Log exception!
throw new ExceptionInInitializerError(ex);
}
}
But it just loads my configuration from hibernate.cfg.xm and do not changing any property...
但它只是从 hibernate.cfg.xm 加载我的配置并且不改变任何属性......
url, username, passoword - are command-line arguments so i must set them on runtime.
url、用户名、密码 - 是命令行参数,所以我必须在运行时设置它们。
回答by Alexey Ogarkov
Try to call conf.configure();here.
And properties may need to have hibernate prefix like "hibernate.connection.username"
Hope it helps.
试着打电话给conf.configure();这里。
并且属性可能需要像“hibernate.connection.username”这样的hibernate前缀
希望它有所帮助。
回答by Aditya Singh
Try like this it is working fine
像这样尝试它工作正常
AnnotationConfiguration conf = new AnnotationConfiguration().configure("/dronehibernate.cfg.xml");
conf.setProperty("hibernate.connection.url","jdbc:mysql://localhost/PAT_DRONE_DB1");
SessionFactory sessionFactory = conf.buildSessionFactory();
Session session = sessionFactory.openSession();
List<NetworkType> channelList = session.createQuery("from NetworkType").list();
回答by Serge Bogatyrev
Use constants from Environmentclass
使用Environment类中的常量

