Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between lazy and eager loading in Hibernate
Lazy and Eager are two data loading strategies used in ORM frameworks such as Hibernate and EclipseLink. These strategies determine when related entities are fetched from the database − for example, when an Employee entity has a reference to a collection of Phone entities.
Lazy Loading
Lazy Loading means associated data is loaded only when you explicitly access it (by calling a getter or size method). Until that point, the related data is not fetched from the database.
Use Lazy Loading when −
- You are working with one-to-many or many-to-many collections.
- You are not always going to use the related entities.
Example
@OneToMany(fetch = FetchType.LAZY) private List<Phone> phones; // phones are NOT loaded when Employee is fetched // phones are loaded only when you call: employee.getPhones(); // triggers SQL query here
Eager Loading
Eager Loading means associated data is loaded immediately at the time the parent entity is fetched. A single query (or a join) fetches both the parent and all related entities together.
Use Eager Loading when −
- The number of related entities is small and predictable.
- You are sure you will need the related entities everywhere the main entity is used.
Example
@OneToMany(fetch = FetchType.EAGER) private List<Phone> phones; // phones are loaded immediately when Employee is fetched // no additional query needed when calling: employee.getPhones(); // already in memory
How They Work
Key Differences
| Feature | Lazy Loading | Eager Loading |
|---|---|---|
| Fetching strategy | Data loads only when getter or size is called | Data loads immediately with the parent entity |
| Default for |
@OneToMany, @ManyToMany
|
@ManyToOne, @OneToOne
|
| Configuration | fetch = FetchType.LAZY |
fetch = FetchType.EAGER |
| Performance | Faster initial load, extra queries later | Slower initial load, no extra queries |
| Risk | LazyInitializationException if session is closed | Loading too much unused data |
Conclusion
Use Lazy Loading when related data is large or not always needed, and Eager Loading when related data is small and always required. Choosing the right strategy helps balance between fewer database queries and faster initial load times.
