What is Hibernate N+1 Problems and its Solution

Hibernate n+1 problems only comes for one to many relationship.

Let us see this problem by example – We have Department table with a one-to-many relationship with Employee. One Department may have many Employees.

Table Department

1 Department 1
2 Department 2
3 Department 3

Table Employee

1 1 Employee Name 1
2 1 Employee Name 2
3 1 Employee Name 3

We have written the Hibernate Department Entity as below.

package com.javaconnect;

public class Department {

	private Long id;
	private Employee[] Employees;

So now you want to print out all the details of Employee models. A native O/R implementation would SELECT all Department and then do N additional SELECTs for getting the information of Employee for each department.

-- To Get all Departments
SELECT * FROM Department;

-- To get each Employee, get Employee details
SELECT * FROM Employee WHERE Employee.departmentId = ?

As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.

Solution for Hibernate N+1 Problem

Using HQL fetch join

You can use the fetch while using the HQL as below example.

from Department d join fetch d.employees Employee

Hibernate Generated SQL would be similer as –

SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id

Using Criteria query

Criteria criteria = session.createCriteria(Department.class);
criteria.setFetchMode("employees", FetchMode.EAGER);

In both above cases, the query returns a list of Department objects with the Employee initialized, and only one query needs to be run to return all the Department and Employee information required.