Himanshu Sharma
Himanshu Sharma

Reputation: 59

How to configure two database in Hibernate

I have to configure two database on same project by configuring two CFG file,

I tried but it is always use the first configuration file,

May i know how can i use two database on same project

Upvotes: 0

Views: 4447

Answers (2)

Du-Lacoste
Du-Lacoste

Reputation: 12757

You need to have two configuration files.

hibernate-mysql.cfg.xml

hibernate-oracle.cfg.xml

And code should be like this.

mysql configuration

private static SessionFactory sessionAnnotationFactory; 

sessionAnnotationFactory = new Configuration().configure("hibernate-mysql.cfg.xml").buildSessionFactory();

Session session = sessionAnnotationFactory.openSession();

oracle sql configuration

sessionAnnotationFactory = new Configuration().configure("hibernate-oracle.cfg.xml").buildSessionFactory();

Session session = sessionAnnotationFactory.openSession()

Upvotes: 0

CE ZHANG
CE ZHANG

Reputation: 527

In your code, what you need to do is to open two different session factory for different databases. For example:

Configuration configA=new Configuration();//use the default hibernate.cgf.xml file
Congiruration configB=new Configuration.configure('/hibernate_db2.cfg.xml') // use hibernate_db2.cfg.xml under root folder.
SessionFactory sfa=configA.buildSessionFactory();
SessionFactory sfb=configB.buildSessionFactory();

Now, you open different session using different db.

Upvotes: 7

Related Questions