[英]hibernate - how to change properties at runtime
我試圖在hibernate.cfg.xml中更改屬性,但我的代碼不起作用。
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看起來總是一樣的。
要使其工作,您應該使用該Configuration
對象構建sessionFactory
,然后使用該sessionFactory
來獲取會話。
就像是 :
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
文件。
更新配置將更新配置文件中已在內存中讀取的配置。 它不會更新文件本身(大多數情況下,自從war或jar文件讀取后,它是只讀的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.