Configuring Multiple Databases in Hibernate

December 11, 2010

Hibernate

«»

Creating Session Factory object in Hibernate

Each database has its own SessionFactory object.

1
2
SessionFactory sessionFactory1 = new  Configuration().configure("oracleconfig.cfg.xml").buildSessionFactory();
SessionFactory sessionFactory2 = new Configuration().configure("derbyconfig.cfg.xml").buildSessionFactory();

Specify the name of the configuration file as an argument to the configure() method when building the session factory object.
Let us create the test application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package hibernatepack.samples;
 
import java.awt.Choice;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EmployeeTest {
    private static int choice;
    public static void main(String[] args) {
        EmployeeDaoImpl empOperations = new EmployeeDaoImpl();
        Employee e1 = new Employee();
        do {
            System.out.println("1. Insert ");
            System.out.println("2. List ");
            System.out.println("3. Exit ");
            System.out.println("Enter your choice ");
            Scanner sc = new Scanner(System.in);
            choice = sc.nextInt();
            switch (choice) {
                case 1:
                    System.out.println("Enter the employee Number ");
                    Scanner sc1 = new Scanner(System.in);
                    int empid = sc1.nextInt();
                    System.out.println("Enter the employee Name ");
                    Scanner sc2 = new Scanner(System.in);
                    String empname = sc2.nextLine();
                    System.out.println("Enter the Salary ");
                    Scanner sc3 = new Scanner(System.in);
                    double empsal = sc3.nextDouble();
                    e1.setEmpid(empid);
                    e1.setEmpname(empname);
                    e1.setSalary(empsal);
                    empOperations.insertEmployee(e1);
                    break;
                case 2:
                     empOperations.findAllEmployees();
                    break;
            }
        } while (choice != 3);
    }
}

When you execute the insert method, table named “HBEMPLOYEEDETAILS” is created both in Oracle and in Derby. Find below the sample output screen.

Conclusion

This is very simple example on how to configure the multiple databases using Hibernate configuration files. In the next weeks I will be writing few more examples on configuring the databases and fetching the data. In the following section you can find the interesting articles related to Hibernate framework.

email

«»

Comments

comments