Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate - how to change properties at runtime

I am trying to change properties in hibernate.cfg.xml but my code doesn't work.

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); 

}

Any idea why thats doesnt work? My file hibernate.cfg.xml always looks the same.

like image 798
Mariola Avatar asked Jul 21 '13 17:07

Mariola


People also ask

How many ways we can configure database properties in Hibernate?

You can configure Hibernate mainly in three ways: Use the APIs (programmatically) to load the hbm file along with the database driver providing connection details. By specifying the database connection details in an XML configuration file that's loaded along with the hbm file.


1 Answers

To make it work, you should build your sessionFactory with that Configuration object and then use that sessionFactory to get your session.

Something like :

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;
}

But at the end, it will not change the hibernate.cfg.xml file, it overwrite or defines properties at runtime. If you don't want to put your username and password in the hibernate.cfg.xml file, you should probably use a .properties file that contain these values.

like image 130
Jean-Philippe Bond Avatar answered Sep 30 '22 12:09

Jean-Philippe Bond