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:
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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With