休眠-如何在运行时更改属性 [英] hibernate - how to change properties at runtime
问题描述
我正在尝试更改hibernate.cfg.xml中的属性,但是我的代码无法正常工作。
I am trying to change properties in hibernate.cfg.xml but my code doesn't work.
public static void changeConfiguration(String login, String password){
Configuration cfg = new Configuration();
cfg.configure();
cfg.setProperty("hibernate.connection.password", password);
cfg.setProperty("hibernate.connection.username", login);
}
有人知道那为什么不起作用吗?我的文件hibernate.cfg.xml始终看起来相同。
Any idea why thats doesnt work? My file hibernate.cfg.xml always looks the same.
推荐答案
要使其正常运行,您应该构建 sessionFactory
和该 Configuration
对象,然后使用该 sessionFactory
进行会话。
To make it work, you should build your sessionFactory
with that Configuration
object and then use that sessionFactory
to get your session.
类似的东西:
public static SessionFactory changeConfiguration(String login, String password){
Configuration cfg = new Configuration();
cfg.configure();
cfg.setProperty("hibernate.connection.password", password);
cfg.setProperty("hibernate.connection.username", login);
SessionFactory sessionFactory = cfg.buildSessionFactory();
return sessionFactory;
}
但最后,它不会更改 hibernate.cfg.xml
文件,它会在运行时覆盖或定义属性。如果您不想将用户名和密码放在 hibernate.cfg.xml
文件中,则可能应该使用 .properties $包含这些值的c $ c>文件。
But at the end, it will not change the hibernate.cfg.xml
file, it overwrite or defines properties at runtime. If you don't want to put your username and password in the hibernate.cfg.xml
file, you should probably use a .properties
file that contain these values.
这篇关于休眠-如何在运行时更改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!