Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java hibernate-如何在运行时更改属性_Java_Database_Hibernate - Fatal编程技术网

Java hibernate-如何在运行时更改属性

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

我正在尝试更改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看起来总是一样的。

更新配置将更新内存中从配置文件读取的配置。它不会更新文件本身(大多数情况下,从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
文件