A fetch profile combines a fetch plan with a fetch strategy. It defines which associations or collections to load and how to load them, then reuses that choice for a unit of work. section 12.0 section 12.4
Hibernate profiles are global metadata but become active only after the Hibernate Session enables them. An enabled profile can override lazy mappings with JOIN fetching for selected associations or collections. section 12.3 section 12.3.1
Use fetch profiles to:
- Load an Item seller with the Item in one SQL statement. section 12.3.1
- Load an Item seller and bids together by enabling multiple profiles in the same unit of work. section 12.3.1
- Optimize fetching for a use case while reducing statement counts and avoiding n+1 selects or Cartesian products. section 12.4
Declare and enable a profile
Package-level metadata can name an Item profile and override seller fetching with FetchMode.JOIN: @FetchProfile(name = Item.PROFILE_JOIN_SELLER, fetchOverrides = @FetchProfile.FetchOverride(entity = Item.class, association = "seller", mode = FetchMode.JOIN)). Enable it with em.unwrap(Session.class).enableFetchProfile(Item.PROFILE_JOIN_SELLER); subsequent Item loads in that EntityManager fetch the seller by join. section 12.3.1 section 12.3.1
Path: Ch12/profile/src/main/java/com/manning/javapersistence/ch12/profile /package-info.java @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 profile has a name. This is a simple string isolated in a constant. #2 Each override in a profile names one entity association or collection. #3 <kbd>FetchMode.JOIN</kbd> means the property will be retrieved eagerly, via a <kbd>JOIN</kbd>.
Inspect the complete annotation structure for named profiles, association overrides, and FetchMode.JOIN. section 12.3.1
