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
Table Student
We have written the Hibernate Class Entity as below.
@Id
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.
Hibernate Generated SQL would be similar as –
Using Criteria query
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 |
ID | CLASS_ID | NAME | ||||||
---|---|---|---|---|---|---|---|---|
1 | 1 | Student Name 1 | ||||||
2 | 1 | Student Name 2 | ||||||
3 | 1 | Student Name 3 |
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
|
private String Studentid; | | | | | |
| | } |
|
|
The SolutionAvoiding Eager FetchingThis 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 |
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 |
1
| SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id |
1
2
| Criteria criteria = session.createCriteria(Department. class ); criteria.setFetchMode( "employees" , FetchMode.JOIN); |
No comments:
Post a Comment