Fetch Profile in Hibernate
Overview
Fetch profiles in Hibernate provide a mechanism to override the default lazy fetch plan for specific entity associations and collections. This feature allows developers to specify eager fetching strategies, such as using JOIN, for a particular unit of work. By using fetch profiles, you can optimize the performance of your application by controlling how and when data is loaded from the database. Fetch profiles are declared using annotations and can be activated through the Hibernate API.
Declaring Hibernate Fetch Profiles
To declare fetch profiles in Hibernate, you use the @FetchProfiles annotation. This annotation allows you to define multiple fetch profiles, each with a specific name and set of fetch overrides. Below is an example of how to declare fetch profiles:
@org.hibernate.annotations.FetchProfiles({
@FetchProfile(name = Item.PROFILE_JOIN_SELLER, #1
fetchOverrides = @FetchProfile.FetchOverride( #2
entity = Item.class,
association = "seller",
mode = FetchMode.JOIN #3
)),
@FetchProfile(name = Item.PROFILE_JOIN_BIDS,
fetchOverrides = @FetchProfile.FetchOverride(
entity = Item.class,
association = "bids",
mode = FetchMode.JOIN
))
})
- #1: Each fetch profile is given a name, which is a simple string stored in a constant.
- #2: Each fetch override within a profile specifies one entity association or collection.
- #3: The
FetchMode.JOINindicates that the property will be retrieved eagerly using a SQLJOIN.
Entity Graphs
Entity graphs, introduced in JPA 2.1, provide another way to define fetch plans. They allow you to specify a graph of entity attributes and associations using the @EntityGraph annotation. This graph can be used as a hint in EntityManager#find() or queries to control what should be loaded. Entity graphs offer a flexible way to manage fetching strategies, complementing the use of fetch profiles in Hibernate.
FAQ (Frequently asked questions)
What are fetch profiles in Hibernate?
How are fetch profiles declared in Hibernate?
How can fetch profiles be activated in Hibernate?
How do you declare a fetch profile in Hibernate?
What does each fetch profile in Hibernate have?
What does FetchMode.JOIN mean in a fetch profile?
What are entity graphs in JPA 2.1?
How can entity graphs be used in JPA?