Difference between lazy and eager loading in Hibernate

Object Oriented ProgrammingProgrammingHibernate

Lazy and Eager are two types of data loading strategies in ORMs such as hibernate and eclipse Link.  These data loading strategies we used when one entity class is having references to other Entities like Employee and Phone (phone in the employee). 

Lazy Loading − Associated data loads only when we explicitly call getter or size method.

  • Use Lazy Loading when you are using one-to-many collections.
  • Use Lazy Loading when you are sure that you are not using related entities. 

Egare Loading − Data loading happens at the time of their parent is fetched.

  •  Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.
  • Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere.
Sr. No.KeyLazyEager
1
Fetching strategy 
In Lazy loading, associated data loads only when we explicitly call getter or size method.
In Eager loading, data loading happens at the time of their parent is fetched 
2
Default Strategy in ORM Layers 
ManyToMany and OneToMany associations used lazy loading strategy by default.
ManyToOne and OneToOne associations used lazy loading strategy by default.
3
Loading Configuration
It can be enabled by using the annotation parameter :

fetch = FetchType.LAZY 
It can be enabled by using the annotation parameter :

fetch = FetchType.EAGER
 4
Performance
Initial load time much smaller than Eager loading
Loading too much unnecessary data might impact performance
raja
Published on 18-Nov-2019 06:16:23
Advertisements