Thursday, January 3, 2019

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 Class table with a one-to-many relationship with Student. One Class may have many Student.

Table Class
ID NAME
1 Class1
2 Class2
3 Class3
Table Student
ID CLASS_ID NAME
1 1 Student Name 1
2 1 Student Name 2
3 1 Student Name 3



We have written the Hibernate Class Entity as below.
package com.javaconnect;
@Entity
public class Class {

       @Id
    private Long class_id;
     
    @OneToMany(cascade = ALL, fetch = EAGER)

   @JoinColumn(name = "class_id")

   private List<Student> student = new ArrayList<>();
}

@Entity

public class Student {
   @Id

    private String class_id;
    private String Studentid;     

 }



-- To Get all Departments
SELECT * FROM Department;
-- To get each Employee, get Employee details
SELECT * FROM Employee WHERE Employee.departmentId = ?





The Solution

Avoiding Eager Fetching

This the main reason behind the issue. We should get rid of all the eager fetching from our mapping. We should mark all relationships as Lazy instead.

 Only fetching the data that are actually needed

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.

1
from Department d join fetch d.employees Employee
Hibernate Generated SQL would be similar as –

1
SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id
Using Criteria query

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

No comments:

Post a Comment

Spring Annotations