In Hibernate/JPA, Lazy Loading and Eager Loading define how and when related data is fetched from the database.
They are mainly used in entity relationships like OneToMany, ManyToOne, etc.
What is Lazy Loading?
Lazy Loading means data is not loaded immediately. It is fetched only when it is actually needed.
π Improves performance by reducing unnecessary data loading.
Example:
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;
π Orders are loaded only when you access orders.
What is Eager Loading?
Eager Loading means data is loaded immediately along with the parent entity.
π Useful when related data is always required.
Example:
@OneToMany(fetch = FetchType.EAGER)
private List<Order> orders;
π Orders are fetched along with the main entity.
Key Differences
| Feature | Lazy Loading | Eager Loading |
|---|---|---|
| Data Fetching | On demand | Immediately |
| Performance | Better (if used properly) | Can be slower |
| Memory Usage | Less | More |
| Use Case | Large data | Small/required data |
Example Scenario
Lazy Loading
- Load User data first
- Fetch Orders only when needed
Eager Loading
- Load User + Orders together
Advantages & Disadvantages
Lazy Loading
β Better performance
β Saves memory
β May cause LazyInitializationException
Eager Loading
β Easy to use
β No extra queries later
β Can load unnecessary data
β Performance issues with large datasets
When to Use
- Use Lazy Loading for large relationships
- Use Eager Loading when related data is always required
Conclusion
Lazy vs Eager Loading is an important concept in Hibernate that directly impacts application performance and memory usage. Choosing the right strategy helps build efficient and scalable applications.
π Learn Java & Backend Development
Upgrade your skills with Best Core JAVA Online Training.
Top comments (0)