hibernate

Hibernate Join Example

Join statements are used when one wants to fetch data from multiple tables of database. Hibernate provides support for join statements where one can write single query to fetch data from multiple tables easily. Hibernate is one of the few JPA (Java Persistence API) providers. Hibernate is extensively used for persistence layer of building an enterprise application. We will show an example where we will fetch data from multiple tables.

1. Introduction

In this post, we will be showing how to use a JOIN statement in hibernate to fetch data from multiple entities which will be mapped to respective databases.

2. Environment

  1. Windows 7
  2. Java version 7
  3. Eclipse Kepler 4.3
  4. Maven 3.0.4
  5. MySQL 5.0.86
  6. JBoss-Hibernate Plugin 4.1.2

3. Example Outline

We will create a maven project, add the required dependencies, add entity classes, create a test program to describe join example with hibernate.

4. Example

Following is a step by step guide to show hibernate join statement.

4.1 Create a Maven project

Create a new maven project in eclipse. Fill in the details for GroupId as com.javacodegeeks.example and ArtifactId as HibernateJoinExample .

Maven Project for Hibernate Join Example
Maven Project for Hibernate Join Example

4.2 Add Hibernate Dependencies

Let’s add hibernate dependencies in pom.xml so we can use hibernate.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.example</groupId>
	<artifactId>HibernateJoinExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.11.Final</version>
		</dependency>
	</dependencies>
</project>

4.3 Create Hibernate Configuration File

Now we will create a Hibernate configuration file hibernate.cfg.xml under resources directory in our maven project. The hibernate wizard will look like below:

Hibernate Configuration File
Hibernate Configuration File

When you create hibernate configuration xml file, check the checkbox for “Create a console configuration”. The file will look like below:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/hbtutorial</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>

4.4 Create entities

In this example, we will be reading all the employees which belong to Marketing department. So we will establish relationship between two entities Employee and Department .

Employee.java

package com.javacodegeeks.example;

public class Employee 
{
	private Long id;
	
	private String firstname;
	
	private String lastname;
	
	private Department department;
	
	public Employee()
	{
		
	}
	
	public Employee(String firstname, String lastname)
	{
		this.setFirstname(firstname);
		this.setLastname(lastname);
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}		
}

Department.java

package com.javacodegeeks.example;

import java.util.Set;

public class Department 
{
	private Long id;
	
	private String departmentName;
	
	private Set employees;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getDepartmentName() {
		return departmentName;
	}

	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}

	public Set getEmployees() {
		return employees;
	}

	public void setEmployees(Set employees) {
		this.employees = employees;
	}
		
}

4.5 Map Java objects to database

We will create a mapping file for each java object to database. In eclipse, under src > main > resources, create a file with option Hibernate XML Mapping file (hbm.xml). We will create Employee.hbm.xml and Department.hbm.xml

Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 5, 2016 12:36:38 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javacodegeeks.example.Employee" table="EMPLOYEE">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="firstname" type="java.lang.String">
            <column name="FIRSTNAME" />
        </property>
        <property name="lastname" type="java.lang.String">
            <column name="LASTNAME" />
        </property>
        <many-to-one name="department" class="com.javacodegeeks.example.Department" fetch="join">
            <column name="DEPARTMENT_ID" />
        </many-to-one>
    </class>
</hibernate-mapping>

Department.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 5, 2016 12:36:38 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javacodegeeks.example.Department" table="DEPARTMENT">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="departmentName" type="java.lang.String">
            <column name="DEPT_NAME" />
        </property>
        <set name="employees" table="EMPLOYEE" inverse="false" lazy="true">
            <key>
                <column name="DEPARTMENT_ID" />
            </key>
            <one-to-many class="com.javacodegeeks.example.Employee"/>
        </set>
    </class>
</hibernate-mapping>

4.6 Hibernate Test Program

Following we show a test program to read data from table. The query we are trying to perform through hibernate is to read all employees of “Marketing” department.

HibernateTestProgram.java

package com.javacodegeeks.example;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateTestProgram {

	private static SessionFactory factory;
	private static ServiceRegistry serviceRegistry;
	
	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		
	        Configuration config = new Configuration();
			config.configure();
			config.addAnnotatedClass(Department.class);
			config.addResource("Department.hbm.xml");
			config.addAnnotatedClass(Employee.class);
			config.addResource("Employee.hbm.xml");
			
			serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
			factory = config.buildSessionFactory(serviceRegistry);
			HibernateTestProgram hbp = new HibernateTestProgram();
			
			List marketingEmployees = hbp.readMarketingEmployees();
			System.out.println(" List of Employees from Marketing Department are : " );
			for(int i = 0; i < marketingEmployees.size(); i++)
			{
				Employee e = marketingEmployees.get(i);
				System.out.println(e.getFirstname() + " " + e.getLastname());
			}

	}
	
	private List readMarketingEmployees()
	{
		// Read all employees which belong to Marketing department 		
		String hql = "FROM Employee where department.departmentName like :dept_name";
		Session session = factory.openSession();
		
		Query query = session.createQuery(hql);
		query.setParameter("dept_name", "Marketing");
		
		List listResult = query.list(); 
		
		return listResult;
	}

}

In this program, there is a method readMarketingEmployees , in which we have shown an example of hibernate join.

String hql = "From Employee where department.departmentName like:dept_name" . This statement shows an implicit join statement which is by default an inner join. The statement is an inner join on dept_id as Employee object has department as foreign key.

If you run this program, the output will be like below:

Hibernate Test Program Output
Hibernate Test Program Output

5. Conclusion

In this example, we showed how to use hibernate to read data from multiple database tables using Hibernate Join statement.

6. Download

The source code for this example is packages in a zip file to download.

Download
You can download the full source code of this example here: hibernatejoinexample

Yogesh Mali

Yogesh currently lives in Minneapolis and works as a Senior Software Engineer. He has a masters degree in Computer Science from University of Minnesota, Twin Cities. At graduate school, he did research in programming languages because of his love for functional and object oriented programming. Currently he delves into more details of Java, web development and security. Previously he worked as a product manager to create web application for health insurance brokers. In his free time, he listens to music and writes fictional stories.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Roger D Pack
2 years ago

SQL for creating the tables please?

Back to top button