22 Dec 2014

Interacting With Multiple Databases 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.


Let us see a step by step procedure by creating a Java Project to create different session factories in order to interact with different databases in Hibernate. Here, in this example we will use two different databases Postgresql and MySql.

1. Create a new Java Project

In Eclipse, Create a new Java Project as 'Hibernate_App'.

2. Update Build Path (Adding all required jars)

In order to use Hibernate in our project we have to update Java Build Path as shown below:
  1. Right click on project and select properties.



  2. Select Java Build Path(1) and then Libraries(2).

  3. Click on Add External Jars(3) and select all required jar files to run a project using Hibernate and click Ok(4). We have updated the build path for our project to use Hibernate.

3. Create a Model Class

In project explorer, right click on src folder and create a package with name javakart in which we will create all our .java files of our project.

Create a class Person.java inside javakart package as shown below:

Person.java
package javakart;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="PERSON")
public class Person{

   @Id
   @Column(name="person_id")
   private Integer personId;
 
   @Column(name="name")
   private String name;

   // Getters & Setters
   public Integer getPersonId(){
      return personId;
   }
   public void setPersonId(Integer personId){
      this.personId = personId;
   }

   public String getName(){
      return name;
   }
   public void setName(String name){
      this.name = name;
   }

}

4. Create HibernateUtil.java and Main.java for accessing data to & from database

HibernateUtil.java
package javakart;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil{

   @SuppressWarnings("deprecation")
   private static SessionFactory buildSessionFactory(String configFile){
      try{
         return new Configuration().configure(configFile).buildSessionFactory();
      }catch(Throwable ex){
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
   }

   public static Session openSession(String configFile){
      SessionFactory sf = buildSessionFactory(configFile);
      return sf.openSession();
   }
}

Main.java
package javakart;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Main{

   public static void main(String args[]){
      Person p1 = new Person();
      p1.setPersonId(101);
      p1.setName("John");
  
      storeIntoPostgres(p1);
      storeIntoMySql(p1);
   }
 
   public static void storeIntoPostgres(Person p1){
      try{
         Session s = HibernateUtil.openSession("postgres-hibernate.cfg.xml");
         Transaction tx = s.beginTransaction();
   
         s.save(p1);
         tx.commit();
         s.flush();
         s.close();
      }catch(Exception ex){
         System.out.println("Error: "+ex.getMessage());
      }
   }
 
   public static void storeIntoMySql(Person p1){
      try{
         Session s = HibernateUtil.openSession("mysql-hibernate.cfg.xml");
         Transaction tx = s.beginTransaction();
   
         s.save(p1);
         tx.commit();
         s.flush();
         s.close();
      }catch(Exception ex){
         System.out.println("Error: "+ex.getMessage());
      }
   }

}

5. Configure Hibernate Configuration File

Inside src folder, create two xml files and update them as shown below:

postgres-hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost/
                                   Hibernate_Practice</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">mypassword</property>
    <property name="connection.pool_size">10</property>
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.internal
                                            .NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    
    <mapping class="javakart.Person"/>

  </session-factory>

</hibernate-configuration>

mysql-hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/
                                   Hibernate_Practice</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">mypassword</property>
    <property name="connection.pool_size">10</property>
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.internal
                                            .NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    
    <mapping class="javakart.Person"/>
  </session-factory>

</hibernate-configuration>

6. Final Project Structure

Finally, our project structure will looks as shown in screenshot:

7. Run the Application

Try to run Main.java. In console we will find the output as:
Hibernate: insert into PERSON (name, person_id) values (?, ?)
Hibernate: insert into PERSON (name, person_id) values (?, ?)





Popular Posts

Write to Us
Name
Email
Message