Last Updated on 26 September 2019   |   Print Email
In this post, I will share with you how to configure database connection information for a Hibernate in a programmatic way, rather than using XML in hibernate.cfg.xml file. Programmatic configuration can be useful in case you need to dynamically update the connection information at runtime, e.g. changing database type or database name.First, create a new Configuration object and set the connection information like this:
The configuration information is as same as in the hibernate.cfg.xml which you would normally do.And if you use annotated model classes, specify each one like this:
Then Hibernate will find the .hbm.xml files corresponding to the class names.Then build a SessionFactory from the Configuration object, and open a Session normally:
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
// working with the session
session.close();
sessionFactory.close();
For your reference, following is an example program that uses programmatic configuration for Hibernate:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Good morning Nam Ha Minh, my name is Gustavo, I'm using google translator because I don't speak English, I hope you're sorry for any mistakes I'm Brazilian, I'm looking for this solution for some time, but unfortunately your toturial isn't working in my application, in your tutorial you uses the hibernate.cfg.xml file, in my application I need the same solution, but I use the persistence.xml file, hibernate 5.5, if you can help me how do I do this configuration using this way? thank you so much
Comments
Let me find out how to configure JPA programmatically then I'll let you know.