Skip to lesson

Lazy vs eager fetching

A ShopLite product list feels instant with 14 rows, then one mapping line makes every list page send extra SQL that nobody asked for. Whether a link loads early or late decides how many statements a page sends.

Fetch types: LAZY and EAGER

A fetch type is the fetch attribute of a relationship annotation. It decides when Hibernate loads the entity at the other end of a link: EAGER together with the owner, LAZY when the code first reads it.

ShopLite's Product has a category link, and its annotation decides when that category loads. These lines show the JPA defaults and the one line ShopLite writes instead.

Java
@ManyToOne                               // EAGER by default@OneToOne                                // EAGER by default@OneToMany(mappedBy = "customer")        // LAZY by default@ManyToMany                              // LAZY by default
@ManyToOne(fetch = FetchType.LAZY)       // what ShopLite writes for every link

Example 1 · findById with EAGER links: one product, three tables

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// Product.java (fragment): no fetch attribute, so the default EAGER applies@ManyToOne@JoinColumn(name = "category_id")private Category category;
// Category.java (fragment): the parent link is EAGER by default too@ManyToOne@JoinColumn(name = "parent_id")private Category parent;
// LabDemos.java (fragment)public void findOneProduct() {    Product p = products.findById(1).orElseThrow();    System.out.println("Product: " + p.getName());}
Sample output
DEBUG SQL - select p1_0.product_id,p1_0.is_active,c1_0.category_id,c1_0.name,p2_0.category_id,p2_0.name,p2_0.parent_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 left join categories c1_0 on c1_0.category_id=p1_0.category_id left join categories p2_0 on p2_0.category_id=c1_0.parent_id where p1_0.product_id=?
Product: Redmi Note 13 5G

What this code does

  • The plain @ManyToOne is EAGER, so Hibernate joins categories to load the product's category, and joins categories again for that category's EAGER parent.
  • The code only printed the product name. The two joins and their columns were loaded for nothing.

Links to one entity are EAGER by default: @ManyToOne and @OneToOne. Links to many entities are LAZY by default: @OneToMany and @ManyToMany. So Product.category, written as a plain @ManyToOne, is EAGER even though you never asked for it.

With findById, EAGER looks harmless: Hibernate adds a left join and loads everything in one statement. Example 1 shows the hidden cost. EAGER spreads along the chain: the category's own EAGER parent link is joined too, so one product read touches three tables.

The perf-lab project used in this module is a small Spring Boot 4.1 app on the ShopLite tables, set up like the labs of earlier modules: Category, Product, Customer, Address, Order and OrderItem entities, ddl-auto=validate, and org.hibernate.SQL logged at DEBUG. A runner calls one demo method per run.

EAGER on a list query: extra SELECTs nobody asked for

A fetch graph is a JPA hint, jakarta.persistence.fetchgraph, that lists the links to load for one query. Every link that is not in the graph is treated as lazy.

ShopLite's product list never uses a category, yet it pays for one. Example 2 counts the SELECTs that run before the loop starts, and Example 3 shows the one per-query escape.

Example 2 · A list query with EAGER links: 1 + 6 SELECTs

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// LabDemos.java (fragment). Product.category and Category.parent are still EAGER.public void listProducts() {    List<Product> list = products.findByActiveTrueOrderByIdAsc();    System.out.println("Loaded " + list.size() + " products");    Product first = list.get(0);    System.out.println("category class: " + first.getCategory().getClass().getSimpleName());    System.out.println("category id: " + first.getCategory().getId());    System.out.println("category name: " + first.getCategory().getName());}
Sample output
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id
DEBUG SQL - select c1_0.category_id,c1_0.name,p1_0.category_id,p1_0.name,p1_0.parent_id from categories c1_0 left join categories p1_0 on p1_0.category_id=c1_0.parent_id where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,p1_0.category_id,p1_0.name,p1_0.parent_id from categories c1_0 left join categories p1_0 on p1_0.category_id=c1_0.parent_id where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,p1_0.category_id,p1_0.name,p1_0.parent_id from categories c1_0 left join categories p1_0 on p1_0.category_id=c1_0.parent_id where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,p1_0.category_id,p1_0.name,p1_0.parent_id from categories c1_0 left join categories p1_0 on p1_0.category_id=c1_0.parent_id where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,p1_0.category_id,p1_0.name,p1_0.parent_id from categories c1_0 left join categories p1_0 on p1_0.category_id=c1_0.parent_id where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,p1_0.category_id,p1_0.name,p1_0.parent_id from categories c1_0 left join categories p1_0 on p1_0.category_id=c1_0.parent_id where c1_0.category_id=?
Loaded 14 products
category class: Category
category id: 2
category name: Mobiles

What this code does

  • The derived query selects only products columns. To fill the EAGER category links, Hibernate then runs one SELECT per distinct category: 2, 3, 4, 5, 6 and 7 (Electronics came along as Mobiles' parent).
  • All 6 extra SELECTs ran before the first println. The class is plain Category: EAGER links hold real objects, not proxies.

Example 3 · The only per-query escape: an empty fetch graph

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// LabDemos.java (fragment). The mappings are still EAGER.public void emptyFetchGraph() {    var graph = em.createEntityGraph(Product.class);    List<Product> list = em.createQuery("select p from Product p where p.active = true order by p.id", Product.class)            .setHint("jakarta.persistence.fetchgraph", graph)            .getResultList();    System.out.println("Loaded " + list.size() + " products with an empty fetch graph");}
Sample output
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id
Loaded 14 products with an empty fetch graph

What this code does

  • jakarta.persistence.fetchgraph with a graph that names no attributes tells Hibernate 7 to treat every link outside the graph as lazy, so only one SELECT runs.
  • It fixes this one query only. Every other query on Product still pays the EAGER cost unless it carries the same hint.

Eager loading on a query means that after a JPQL or derived query returns, Hibernate loads every EAGER link before it hands you the list. findByActiveTrueOrderByIdAsc() has no join, so Hibernate sends one more SELECT per distinct category: 1 + 6 = 7 statements for 14 products, and 101 with 100 categories. The method never used a category, but every caller pays on every call.

A plain query has no switch to make an EAGER link lazy. The fetch graph hint of Example 3 is the only escape, and every query must remember it: one forgotten method brings the extra SELECTs back. That is why the mapping itself should be LAZY.

Predict the output

How many SELECTs?

14 active products in 6 categories. Count the statements before the println.

Round 1 of 3

Product.category is a plain @ManyToOne.

List<Product> list = products.findByActiveTrueOrderByIdAsc();
System.out.println(list.size());
Why not a join? JPQL runs exactly the query you wrote. Hibernate adds joins for EAGER links only when it builds the SQL itself, as in findById.

Proxies: getId() on a lazy link without a SELECT

A proxy is a stand-in object that Hibernate puts in a LAZY link field. It is a generated subclass of your entity that knows only the id and loads the real row the first time another getter is called.

With a LAZY @ManyToOne, the product's category field is not a real category yet. Example 4 prints its id, then its name, and the log shows when the SELECT runs.

Example 4 · LAZY: one SELECT, a proxy, and a SELECT only for the name

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// Product.java (fragment): the link is now LAZY@ManyToOne(fetch = FetchType.LAZY)@JoinColumn(name = "category_id")private Category category;
// LabDemos.java (fragment): the same method as beforepublic void listProducts() {    List<Product> list = products.findByActiveTrueOrderByIdAsc();    System.out.println("Loaded " + list.size() + " products");    Product first = list.get(0);    System.out.println("category class: " + first.getCategory().getClass().getSimpleName());    System.out.println("category id: " + first.getCategory().getId());    System.out.println("category name: " + first.getCategory().getName());}
Sample output
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.product_id
Loaded 14 products
category class: Category$HibernateProxy
category id: 2
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
category name: Mobiles

What this code does

  • The list costs one statement. The category field holds a Category$HibernateProxy that knows its id, so getId() prints 2 with no SQL.
  • getName() is the first real use, so the proxy runs select ... where category_id=? at that moment, exactly once.

The proxy class is named like Category$HibernateProxy. It knows the id from the category_id column of the product row, so getId() needs no SQL. The first call to any other getter, such as getName(), runs one select ... where category_id=? and fills the proxy; later calls use the loaded data.

Two traps come with proxies. Reading a lazy getter after the transaction has ended throws LazyInitializationException, as the Persistence Context module showed. And getClass() on a proxy returns the generated subclass, so an equals that compares getClass() calls a proxy and a loaded entity different. Use instanceof in entity equals.

The rule: map everything LAZY, fetch per use case

With every link LAZY, each query decides what it loads. Example 5 repeats the findById of Example 1 with LAZY links.

Example 5 · The same findById with LAZY links: one plain SELECT

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// Product.java and Category.java: both @ManyToOne links are LAZY now@ManyToOne(fetch = FetchType.LAZY)@JoinColumn(name = "category_id")private Category category;
// LabDemos.java (fragment)public void findOneProduct() {    Product p = products.findById(1).orElseThrow();    System.out.println("Product: " + p.getName());}
Sample output
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
Product: Redmi Note 13 5G

What this code does

  • Compare with Example 1: no joins, only the seven products columns. The category stays a proxy until someone needs it.
  • If a screen does need the category name, its query asks for it with a fetch join or an entity graph (the Fixes lesson).

Map every association LAZY and decide what to load in each query. One screen needs products with category names, another only product names, so each query fetches exactly what its screen needs, using JOIN FETCH, @EntityGraph, batch fetching or a DTO query (next lessons). LAZY alone does not make an app fast: a loop that reads a lazy link for every row is the N+1 problem of the next lesson. The difference is control: EAGER costs SQL that no query can avoid, while LAZY costs SQL only where code uses the link, and each use can be fixed in one place. In an interview, say: "Every @ManyToOne gets fetch = LAZY, because EAGER cannot be turned off per query and loads extra rows on every list."

Four habits keep the mapping healthy:

  • @ManyToOne(fetch = FetchType.LAZY) and @OneToOne(fetch = FetchType.LAZY): always write it.
  • @OneToMany and @ManyToMany: already LAZY; never change them to EAGER.
  • Read lazy links only inside a transaction (in the service), never in the controller.
  • Check the SQL log after every new query: count the statements, not just the result.

Find the bug

Find the risky mapping

Each snippet has one line that loads too much or breaks later. Tap it.

The category link of a product.

Round 1 of 3

Next step

Check your understanding

11 quick questions