hibernate FetchType
hibernate FetchType
Default FetchType
Depends on the cardinality of the relationship
- All to-one relationships use FetchType.EAGER
- all to-many relationships FetchType.LAZY
Loading
- Eager Loading is a design pattern in which data initialization occurs on the spot
- Lazy Loading is a design pattern which is used to defer initialization of an object as long as it's possible
|
One User can have multiple OrderDetails. In eager loading strategy, if we load the *User* data, it will also load up all orders associated with it and will store it in a memory.
But, when lazy loading is enabled, if we pull up a UserLazy, OrderDetail data won't be initialized and loaded into a memory until an explicit call is made to it.
List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list(); |
the main difference between the two types of fetching is a moment when data gets loaded into a memory.
With the lazy initialization approach, orderDetailSet will get initialized only when it is explicitly called by using a getter or some other method as shown in the above example:
But with an eager approach in UserEager it will be initialized immediately in the first line of above example:
Pros and Cons
LazyLoading
Advantages:
- Initial load time much smaller than in the other approach
- Less memory consumption than in the other approach
Disadvantages:
- Delayed initialization might impact performance during unwanted moments
- In some cases you need to handle lazily-initialized objects with a special care or you might end up with an exception
EagerLoading
Advantages:
- No delayed initialization related performance impacts
Disadvantages:
- Long initial loading time
- Loading too much unnecessary data might impact performance
https://www.baeldung.com/hibernate-lazy-eager-loading
Lazy Collection