Java hibernate-如何在运行时更改属性
我正在尝试更改hibernate.cfg.xml中的属性,但我的代码不起作用Java hibernate-如何在运行时更改属性,java,database,hibernate,Java,Database,Hibernate,我正在尝试更改hibernate.cfg.xml中的属性,但我的代码不起作用 public static void changeConfiguration(String login, String password){ Configuration cfg = new Configuration(); cfg.configure(); cfg.setProperty("hibernate.connection.password", password); cfg.se
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看起来总是一样的。更新配置将更新内存中从配置文件读取的配置。它不会更新文件本身(大多数情况下,从war或jar文件读取后,该文件是只读的)。要使其正常工作,您应该使用该
配置对象构建会话工厂,然后使用该会话工厂来获取会话
比如:
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
文件