6

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Updating the configuration will update the configuration that has been read in memory from the configuration file. It won't update the file itself (which, most of the time, is read-only since read from a war or jar file).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.