Fetching strategy
In Java Persistence API (JPA), you can provide a hint to fetch the data lazily or eagerly using the FetchType
implementation. However, some implementations may ignore the lazy strategy and just fetch everything eagerly. Hibernate's default to reduce the memory footprint of your application is FetchType.LAZY
.
Tip
The lazy and eager strategies impact the associated entity. When you set fetch strategy of an associated entity to lazy
, Hibernate will not fetch the associated entity until you access the associated entity. You must access the associated entity in the same session where you fetched the parent entity; otherwise, you will encounter an exception. On the other hand, the eager
fetch strategy forces Hibernate to retrieve the associated entity when the parent entity is fetched.
As mentioned in the previous chapter, Hibernate offers additional fetch modes in addition to the commonly-used JPA fetch types. Here, we will discuss how they are related and provide an explanation...