Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to multiple databases in Hibernate

I am new bee to Hibernate and trying out things. One thing that seems to amuse all is how to connect to different databases? I have two questions here:

  1. If in the same web app I need to connect to MySQL and Oracle, how do I do it?
  2. I am using MySQL and have two databases test1 and test2, how to connect and retrieve data?

I have read in a blog that we can create different configuration files and do it. I tried it but was not sucessful. Here's what I tried:

SessionFactory sf = (SessionFactory) new Configuration().configure(path); 

Where path is the path of the config file. Is this the right way?

like image 308
akellakarthik Avatar asked Dec 17 '09 13:12

akellakarthik


People also ask

Can you connect multiple DBS in hibernate?

In hibernate we can interact with multiple databases within the same application. All we need is to create two different session factories; one to interact with each database.

Is it possible to connect to multiple databases?

Enabling Multiple Database Connections To enable multiple database connections for an archive, extract, or delete process, set Maximum Database Connections in Product Options to a value greater than one. The size of the buffer increases according to the number of database connections that you allow.

How can we connect multiple databases using hibernate spring boot example?

To connect multiple databases, each database should be configured in its own spring boot configuration file. Multiple data sources should be configured for multiple databases. For spring data classes and spring data JPA repositories, two separate java packages need be created.

Can we have multiple sessionFactory in hibernate?

Q. What we can create more than one sessionFactory in Hibernate. Ans And Its true We can create.As in my app i am able to da same.


1 Answers

Using annotation mappings as an example:

Configuration cfg1 = new AnnotationConfiguration(); cfg1.configure("/hibernate-oracle.cfg.xml"); cfg1.addAnnotatedClass(SomeClass.class); // mapped classes cfg1.addAnnotatedClass(SomeOtherClass.class); SessionFactory sf1 = cfg1.buildSessionFactory();  Configuration cfg2 = new AnnotationConfiguration(); cfg2.configure("/hibernate-mysql.cfg.xml"); cfg2.addAnnotatedClass(SomeClass.class); // could be the same or different than above cfg2.addAnnotatedClass(SomeOtherClass.class); SessionFactory sf2 = cfg2.buildSessionFactory(); 

Then use sf1 and sf2 to get the sessions for each database. For mapping files, you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case. Those will have the Oracle or MySQL dialect and connection information.

like image 88
Brian Deterling Avatar answered Sep 23 '22 14:09

Brian Deterling