DEV Community

Gowtham Kalyan
Gowtham Kalyan

Posted on

Lazy vs Eager Loading in Hibernate

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;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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)