liveBook · Manning

FetchType.EAGER

As explained in Java Persistence with Spring Data and Hibernate epub

FetchType.EAGER is a Jakarta Persistence fetch option specifying that an associated value is retrieved with its owning entity.

FetchType.EAGER maps an association so its value is retrieved with the owning entity. It is useful when an Item must retain access to its seller after detachment and persistence-context closure. section 12.2.2 section 12.1

Path: Ch12/cartesianproduct/src/main/java/com/manning/javapersistence/ch12
 /cartesianproduct/Item.java
 
@Entity
public class Item {
    @ManyToOne(fetch = FetchType.EAGER)
    private User seller;
    //  . . .
}

A concrete Hibernate mapping applies FetchType.EAGER to an Item-to-User seller association. section 12.2.2

Hibernate commonly implements eager to-one fetching with one SQL SELECT and JOINs. An Item, seller, address, and city can remain in one result row, but hibernate.max_fetch_depth limits joined traversal; beyond the limit, additional SELECT statements still satisfy the eager plan. section 12.2.2

Eager collections and Cartesian products

Marking both bids and images as FetchType.EAGER can produce one query joining ITEM, BID, and IMAGE. Multiple rows then represent combinations of collection elements, creating the Cartesian product problem and serious performance concerns. section 12.2.2

EAGER is the default for @OneToOne. Nullable one-to-one associations cannot rely on proxy-based lazy loading under the JPA model, while non-optional associations can be mapped LAZY when proxy conditions are satisfied. section 9.1.1

Use eager fetching selectively:

  • Prefer it for narrowly scoped to-one data that must be available outside the persistence context. section 12.2.2
  • Avoid eagerly joining multiple collections; use a lazy default and override loading per use case when necessary. section 12.2.2 section 12.1
  • Tune hibernate.max_fetch_depth carefully because deeper eager graphs can shift from JOINs to additional SELECT statements. section 12.2.2

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains JOIN execution, fetch-depth limits, fallback SELECTs, proxy constraints, and Cartesian products.
Examples
Uses Item-seller loading, eager bids and images, generated SQL, and detached collection assertions.
What it assumes
Assumes entity associations and persistence contexts while contrasting eager loading with lazy loading and proxies.
What you can do after
Evaluate eager mappings, configure fetch depth, and diagnose JOIN-based performance problems.
How it connects
Connects fetch plans with lazy loading, SQL JOINs, entity detachment, proxies, one-to-one mappings, and Cartesian products.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.