Hibernate two table join Example

Hibernate two table join Example

Step 1: Download the hibernate 3.6 final distribution.

Click to download Hibernate 3.6 final distribution download.

Step 2: Required jar files are,

required library files for hibernate

Step 3: Create a Java project in the eclipse and Create a hibernate configuration xml file inside src folder (which should be configured with the connections information like url, username password etc…)

Create a file named “hibernate.cfg.xml” and paste the below code,

Note: Filename can be anything but extension must be .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>
        <!-- Database connection configurations -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>

        <!-- Making autocommit false -->
        <property name="hibernate.connection.autocommit">false</property>

        <!-- Displaying sql queries when running the program -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="use_sql_comments">true</property>

        <!-- For JDBC connections -->
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

        <!-- Mapping file -->
        <mapping resource="empNameMapping.hbm.xml"/>
        <mapping resource="empSalaryMapping.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

Note: Url, Username Password and dialect informations are available for all the databases in the configuration file which is in “project -> etc (contains all the properties of all databases)”  of hibernate 3.6 distribution final folder (which is downloaded in step 1).

Step 4: Table structures are,

EMPNAME TABLE (empid int, empname varchar);
EMPSALARY TABLE (empid int, empsalary int); and table holds the below sample informations,

EMPNAME:                                                              EMPSALARY
EMPID         EMPNAME                                    EMPID        EMPSALARY
100              NAVEEN                                       100               5000
101              DIVYA                                            101              9000
102              HEMS                                            102              6000
103              RVS                                               103             11000
104              CHUDAR                                       104              7000

Step 5: Create a Pojo class (EmpName) for the table EMPNAME with the attributes (empId, empName and employeeSalary with the type EmpSalary (class which need to be mapped) for one to one mapping) and paste the below code,


public class EmpName {
	public EmpName(){}
	private int empId;
	private String empName;
	private <strong>EmpSalary employeeSalary;</strong>

	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public EmpSalary getEmployeeSalary() {
		return employeeSalary;
	}
	public void setEmployeeSalary(EmpSalary employeeSalary) {
		this.employeeSalary = employeeSalary;
	}

}

Step 6: Create a another Pojo class (EmpSalary) for the table EMPSALARY with the attributes (empId, empSalary and employeeName with the type EmpName (class which need to be mapped) for one to one mapping) and paste the below code,


public class EmpSalary {
	public EmpSalary(){}
	private int empId;
	private int empSalary;
	private <strong>EmpName employeeName;</strong>
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public int getEmpSalary() {
		return empSalary;
	}
	public void setEmpSalary(int empSalary) {
		this.empSalary = empSalary;
	}
	public EmpName getEmployeeName() {
		return employeeName;
	}
	public void setEmployeeName(EmpName employeeName) {
		this.employeeName = employeeName;
	}

}

Step 7: Create a mapping xml file which map the column and the attribute of the above Pojo class (setter and getter).

Create a file named “empNameMapping.hbm.xml” and paste the below code,

Note: File name can be anything, but extension must be .hbm.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="EmpName" table="EMPNAME">
        <id name="empId" column="EMPID" type="integer">
            <generator class="assigned"></generator>
        </id>

        <strong><one-to-one name="employeeSalary" class="EmpSalary" cascade="save-update"></one-to-one></strong>
        <property name="empName" column="EMPNAME" type="string"></property>
    </class>

</hibernate-mapping>

Copy the doctype(3rd line) from the file (project -> core ->source ->main ->resources -> org ->hibernate ->(mapping file)) for the above mapping file, it is not a mandatory one, to ensure the things right we can do this.

Step 8: Create a another xml mapping file “empNameSalary.hbm.xml” and paste the below code.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="EmpSalary" table="EMPSALARY">
        <id name="empId" column="EMPID" type="integer">
            <generator class="assigned"></generator>
        </id>
        <strong><one-to-one name="employeeName" class="EmpName" constrained="true"></one-to-one></strong>

        <property name="empSalary" column="EMPSALARY" type="integer"></property>
    </class>
</hibernate-mapping>

Step 9: Create a business class named “MainClass” and paste the below code,

import java.util.Iterator;
import java.util.List;

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

public class MainClass {

	public static void main(String[] args) {
		   Configuration cf = new Configuration();
	       cf.configure("hibernate.cfg.xml");
	       SessionFactory sf = cf.buildSessionFactory();
	       Session session = sf.openSession();
	       Transaction t = session.beginTransaction();
	       List nameSalary = session.createQuery("FROM EmpName").list();
	       for(Iterator iter = nameSalary.iterator();iter.hasNext();){
	    	   EmpName en = (EmpName) iter.next();
	    	   System.out.println("Employee Name : "+en.getEmpName());
	    	   EmpSalary es = en.getEmployeeSalary();
	    	   System.out.println("Employee salary "+es.getEmpSalary());
	       }
	}

}

Run the program and the values are fetched from the db and the query will be displayed in the console, since we have configured show sql true in our xml configuration file.

Output:

Hibernate:
/*
FROM
EmpName */ select
empname0_.EMPID as EMPID0_,
empname0_.EMPNAME as EMPNAME0_
from
EMPNAME empname0_
Hibernate:
/* load EmpSalary */ select
empsalary0_.EMPID as EMPID1_0_,
empsalary0_.EMPSALARY as EMPSALARY1_0_
from
EMPSALARY empsalary0_
where
empsalary0_.EMPID=?
Hibernate:
/* load EmpSalary */ select
empsalary0_.EMPID as EMPID1_0_,
empsalary0_.EMPSALARY as EMPSALARY1_0_
from
EMPSALARY empsalary0_
where
empsalary0_.EMPID=?
Hibernate:
/* load EmpSalary */ select
empsalary0_.EMPID as EMPID1_0_,
empsalary0_.EMPSALARY as EMPSALARY1_0_
from
EMPSALARY empsalary0_
where
empsalary0_.EMPID=?
Hibernate:
/* load EmpSalary */ select
empsalary0_.EMPID as EMPID1_0_,
empsalary0_.EMPSALARY as EMPSALARY1_0_
from
EMPSALARY empsalary0_
where
empsalary0_.EMPID=?
Hibernate:
/* load EmpSalary */ select
empsalary0_.EMPID as EMPID1_0_,
empsalary0_.EMPSALARY as EMPSALARY1_0_
from
EMPSALARY empsalary0_
where
empsalary0_.EMPID=?
Employee Name : naveen
Employee salary 5000
Employee Name : divya
Employee salary 9000
Employee Name : hems
Employee salary 6000
Employee Name : rvs
Employee salary 11000
Employee Name : chudar
Employee salary 7000

Easy Understand :

  • Hibernate configuraion xml file which is to hold the connection details such as url, username, password, dialect(to generate queries) and driver class details.
  • Pojo class for the required attributes.
  • Hibernate mapping xml file to map the pojo class attributes with the table columns.
  • Business class to write the business code, we have written value selection details here.

Download the Source Code:

HibernateJoinTwoTables

Recommended Books:

431 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *