休眠-如何在运行时更改属性

Mar*_*ola 5 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.setProperty("hibernate.connection.username", login); 

}
Run Code Online (Sandbox Code Playgroud)

任何想法,为什么那不起作用?我的文件hibernate.cfg.xml总是看起来一样。

Jea*_*ond 5

为了使其工作,您应该sessionFactory使用该Configuration对象构建您的对象,然后使用该对象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;
}
Run Code Online (Sandbox Code Playgroud)

但是最后,它不会更改hibernate.cfg.xml文件,它会在运行时覆盖或定义属性。如果您不想在hibernate.cfg.xml文件中输入用户名和密码,则应使用.properties包含这些值的文件。