English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The Difference Between Lazy Loading and Eager Loading in Hibernate

Lazy and Eager are two data loading strategies in ORM, such as Hibernate and EclipseLink. When an entity class refers to other entities (such as Employee and Phone (phone in Employee)), we use these data loading strategies. 

Lazy loading-Associated data is loaded only when we explicitly call getter or size methods.

  • Use lazy loading when using one-to-many collections.

  • Use 'lazy loading' when you are sure that you are not using related entities. 

Eager loading-Data loading occurs when its parent is retrieved.

  •  When there are not too many relationships, please use 'desire loading'. Therefore, eager loading is a good habit to reduce further queries on the server.

  • Use 'eager loading' when you are sure that you will use the main entity everywhere.

Serial numberKeyLazyEager
1
Fetching strategy 
In lazy loading, associated data is loaded only when we explicitly call getter or size methods.
In eager loading, data loading occurs when its parent is retrieved 
2
Default strategy in ORM layer 
By default, ManyToMany and OneToMany associations use lazy loading strategies.
By default, ManyToOne and OneToOne associations use lazy loading strategies.
3
Loading configuration
It can be enabled by using annotation parameters:

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

fetch = FetchType.EAGER
 4
Performance
The initial loading time is much shorter than eager loading.
Loading too much unnecessary data may affect performance