How to implement Joins in Hibernate?

How to implement Joins in Hibernate?

Explanation of Joins in Hibernate

Hibernate supports various types of joins, which are similar to SQL joins:

  • Inner Join : Returns only the records that have matching values in both tables.
  • Left Join (Left Outer Join) : Returns all records from the left table and the matched records from the right table. The result is NULL from the right side if there is no match.
  • Right Join (Right Outer Join) : Returns all records from the right table and the matched records from the left table. The result is NULL from the left side if there is no match.
  • Full Join (Full Outer Join) : Returns all records when there is a match in either left or right table. Records without a match in the other table will contain NULL.

Joins in Hibernate

Example in Java using Hibernate

We’ll consider two entities: Employee and Department.

Entities Definition:

Employee.java
java
@Entity
@Table(name = "employee")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Getters and Setters
}

Department.java
java
@Entity
@Table(name = "department")
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    // Getters and Setters
}

Inner Join Example
HQL Query using Inner Join:

java

String hql = "SELECT e FROM Employee e INNER JOIN e.department d WHERE d.name = :departmentName";

Query query = session.createQuery(hql);

query.setParameter("departmentName", "HR");

List<Employee> employees = query.list();

 

Left Join Example
HQL Query using Left Join:

java

String hql = "SELECT e FROM Employee e LEFT JOIN e.department d";

Query query = session.createQuery(hql);

List<Employee> employees = query.list();

Right Join Example
HQL Query using Right Join:

java

String hql = "SELECT e FROM Employee e RIGHT JOIN e.department d";

Query query = session.createQuery(hql);

List<Employee> employees = query.list();

 

Full Join Example
HQL Query using Full Join:

java

String hql = "SELECT e FROM Employee e FULL JOIN e.department d";

Query query = session.createQuery(hql);

List<Employee> employees = query.list();

 

Homepage

Readmore