Hibernate Lazy Fetching and Eager Fetching

date
Feb 1, 2024
slug
hibernate-fetching
status
Published
tags
HIBERNATE
summary
type
Post
We will see the difference between hibernate lazy fetching and eager fetching with an example. Let’s define two entities: account and order. An account can have multiple orders.

Account

Here, I have defined the fetch type as lazy.

Order

As the name suggests, the core difference lies now in how hibernate fetches the related entities when the primary entity is fetched. By primary i mean Account entity.

Fetch Lazy

Logs

With the lazy hibernate fetch type, it does not fetch the associated ORDER entities with the account entity when the account is accessed. Unless we specifically call and use the account’s orders by calling getOrder(), orders associated with the account will not be fetched.

Fetch Eager

Defining fetch type as FetchType as Eager

Main

Logs

Here, as we can see whenever account entity is accessed, hibernate also fetch the related ORDER entites in single query.

Conclusion

By setting the fetch strategy to LAZY, we ensure that associated entities are only loaded when explicitly requested, optimizing performance by fetching only the essential data when needed. This approach is particularly beneficial in scenarios where certain associations are seldom utilized during the normal course of operations.
Additionally, employing a LAZY fetch strategy contributes to a more efficient use of memory resources. By deferring the loading of associated entities until necessary, we avoid loading unnecessary data into memory, thus reducing the overall memory footprint of the application. This optimization is crucial for applications with large datasets or those operating in resource-constrained environments.
 

© Rupesh Dang 2021 - 2025