我正在尝试更改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看起来总是一样的。
最佳答案
为了使其工作,您应该使用该sessionFactory
对象构建Configuration
,然后使用该sessionFactory
进行 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
文件。