Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate using multiple databases

I need to have multiple databases for different customers. How can I handle multiple databases with Hibernate? Are there any good examples how to do this?

I could create Configuration object and then build SessionFactory, but that would create always a new session factory which wouldn't be very wise.

EDIT:

Now I can get hibernate Configuration object when user logs in, but how can I create/get session factory with that object so that there would be only one session factory for one database (of course if multiple databases are used at the same time, then there can be more than one session factory)?

like image 497
newbie Avatar asked Feb 27 '23 00:02

newbie


1 Answers

I had the same problem. I solved it like this:

First of all, there should be different cfg.xml files for different databases. Then simply use Configuration object of the Hibernate whenever you want to connect to your second database.

Configuration config = new Configuration().configure("<complete path to your cfg.xml file>");
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();

I found this here : http://www.coderanch.com/t/468821/ORM/java/If-hibernate-cfg-xml-has

I am pretty sure that this can be extended to more than 2 databases. Hope this helps.

like image 200
Bhushan Avatar answered Mar 07 '23 22:03

Bhushan