Skip to lesson

Fixes: JOIN FETCH, @EntityGraph and batch fetching

A ShopLite page that sends 7 or 8 statements needs its links loaded together with the list, not one at a time. JPA offers four tools for that, and each fits a different situation.

JOIN FETCH in JPQL

JOIN FETCH is a JPQL join that also fills the link in the same SELECT. select p from Product p join fetch p.category returns products whose category holds a real, loaded category.

The product list sent 7 statements because each category loaded on its own. Example 1 adds join fetch, and Example 2 fetches a collection.

Example 1 · JOIN FETCH: the product list from 7 statements to 1

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

Java
// ProductRepository.java (fragment)@Query("select p from Product p join fetch p.category where p.active = true order by p.id")List<Product> findActiveWithCategory();
// LabDemos.java (fragment): "fetch" runs findActiveWithCategory(), the default runs the derived querypublic void productNames(String how) {    stats.clear();    List<Product> list = switch (how) {        case "fetch" -> products.findActiveWithCategory();        case "graph" -> products.findWithCategoryByActiveTrueOrderByIdAsc();        default -> products.findByActiveTrueOrderByIdAsc();    };    for (Product p : list.subList(0, 4)) {        System.out.println(p.getName() + " - " + p.getCategory().getName());    }    list.forEach(p -> p.getCategory().getName());    System.out.println(list.size() + " products, statements: " + stats.getPrepareStatementCount());}
// terminaljava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=namesjava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=namesfetch
Sample output
-- names: the plain derived query (N+1)
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,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Redmi Note 13 5G - Mobiles
Samsung Galaxy M35 - Mobiles
iPhone 15 128GB - Mobiles
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Lenovo IdeaPad Slim 3 - Laptops
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
14 products, statements: 7

-- namesfetch: join fetch
DEBUG SQL - select p1_0.product_id,p1_0.is_active,c1_0.category_id,c1_0.name,c1_0.parent_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 join categories c1_0 on c1_0.category_id=p1_0.category_id where p1_0.is_active=true order by p1_0.product_id
Redmi Note 13 5G - Mobiles
Samsung Galaxy M35 - Mobiles
iPhone 15 128GB - Mobiles
Lenovo IdeaPad Slim 3 - Laptops
14 products, statements: 1

What this code does

  • Without the fetch, 14 products in 6 categories cost 1 + 6 statements. With join fetch p.category, the category columns come in the same row and every getCategory().getName() is free.
  • The SQL is an inner join: a product without a category would be dropped. ShopLite products always have one (category_id is NOT NULL).

Example 2 · A collection fetch without DISTINCT: 7 customers, not 16

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

Java
// CustomerRepository.java (fragment): no DISTINCT in the query@Query("select c from Customer c join fetch c.orders order by c.id")List<Customer> findAllWithOrders();
// LabDemos.java (fragment)public void customersWithOrders() {    stats.clear();    List<Customer> list = customers.findAllWithOrders();    System.out.println("Customers in the list: " + list.size());    for (Customer c : list) {        System.out.println(c.getFullName() + ": " + c.getOrders().size() + " orders");    }    System.out.println("Statements: " + stats.getPrepareStatementCount());}
Sample output
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,o1_0.customer_id,o1_0.order_id,o1_0.address_id,o1_0.ordered_at,o1_0.status,c1_0.phone from customers c1_0 join orders o1_0 on c1_0.customer_id=o1_0.customer_id order by c1_0.customer_id,o1_0.order_id
Customers in the list: 7
Asha Rao: 3 orders
Ravi Kumar: 3 orders
Meena Iyer: 2 orders
Kabir Singh: 2 orders
Priya Sharma: 2 orders
Arjun Mehta: 2 orders
Divya Nair: 2 orders
Statements: 1

What this code does

  • The SQL returns 16 rows (one per order), but the list has 7 customers: Hibernate 6 and 7 remove repeated root entities from a fetch-join result by themselves.
  • Imran Khan is missing because join fetch is an inner join and he has no orders. Write left join fetch to keep customers with no orders.

With the join, the loop never needs a proxy, and Example 1 takes the product list from 7 statements to 1. join fetch is an inner join: products without a category would disappear, so use left join fetch when the link may be null. You may also fetch a collection: select c from Customer c join fetch c.orders returns each customer with its orders loaded.

A collection fetch returns one SQL row per child, so Asha Rao appears in 3 rows. Before Hibernate 6 the result list repeated her too, and every guide said to write select distinct c. Since Hibernate 6, duplicates of the root entity are removed automatically: Example 2 returns 7 customers from 16 joined rows with no DISTINCT. Old code with distinct still works; new code does not need it.

@EntityGraph on repository methods

@EntityGraph is a Spring Data annotation on a repository method that lists the links to load together with the query, without writing JPQL. It always uses a left join.

A derived query has no JPQL to add join fetch to. Example 3 shows an annotation on the method that loads the category instead.

Example 3 · @EntityGraph on derived queries

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

Java
// ProductRepository.java (fragment): a derived query plus an entity graph@EntityGraph(attributePaths = "category")List<Product> findWithCategoryByActiveTrueOrderByIdAsc();
// OrderRepository.java (fragment): the same idea for orders and customers@EntityGraph(attributePaths = "customer")List<Order> findByStatusOrderByIdAsc(OrderStatus status);
// terminaljava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=namesgraphjava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=graph
Sample output
-- namesgraph
DEBUG SQL - select p1_0.product_id,p1_0.is_active,c1_0.category_id,c1_0.name,c1_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 where p1_0.is_active=true order by p1_0.product_id
Redmi Note 13 5G - Mobiles
Samsung Galaxy M35 - Mobiles
iPhone 15 128GB - Mobiles
Lenovo IdeaPad Slim 3 - Laptops
14 products, statements: 1

-- graph: PLACED orders with their customers
DEBUG SQL - select o1_0.order_id,o1_0.address_id,c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone,o1_0.ordered_at,o1_0.status from orders o1_0 left join customers c1_0 on c1_0.customer_id=o1_0.customer_id where o1_0.status=? order by o1_0.order_id
Order 15 - Arjun Mehta
Order 16 - Divya Nair
Statements: 1

What this code does

  • Both derived queries keep their WHERE and ORDER BY and get a left join for the graph's attribute, so each list costs one statement.
  • No JPQL was written. The method name findWithCategoryBy... documents what the graph loads; Spring Data ignores the WithCategory part.

@EntityGraph(attributePaths = "category") List<Product> findWithCategoryByActiveTrueOrderByIdAsc() keeps the derived query and adds a left join for the category. The words between find and By (here WithCategory) are ignored by Spring Data, so you can name the method after what it loads. You can also redeclare an inherited method such as findAll(Specification, Pageable) with the annotation; the ShopLite project at the end of this module does exactly that.

Use JOIN FETCH when you already write JPQL, and @EntityGraph for derived queries, findById variants and Specification queries. Both send a join; an entity graph always uses left join, so rows with a null link stay in the result.

Paths can go deeper: attributePaths = {"items", "items.product"} loads an order's items and each item's product in one statement.

Batch fetching: IN queries instead of N SELECTs

Batch fetching keeps lazy loading but loads many proxies at once. When one lazy link is touched, Hibernate loads the other waiting ones of the session with a single where id in (...) query.

Some N+1 code is hard to find or sits inside a mapper. Example 4 leaves the code unchanged and only sets a batch size.

Java
// one link only, instead of the global setting@OneToMany(mappedBy = "parent")@BatchSize(size = 16)                    // org.hibernate.annotations.BatchSizeprivate List<Category> children = new ArrayList<>();

Example 4 · default_batch_fetch_size: the same N+1 code, far fewer statements

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

YAML
# application.yml: one setting for every lazy link and collectionspring:  jpa:    properties:      hibernate:        default_batch_fetch_size: 16# terminal: the unchanged N+1 code (plain derived query, lazy getters in a loop)java -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=namesjava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=n1      # on a database with 20 orders of 20 customers
Sample output
-- names, 14 products in 6 categories
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,c1_0.parent_id from categories c1_0 where c1_0.category_id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
Redmi Note 13 5G - Mobiles
Samsung Galaxy M35 - Mobiles
iPhone 15 128GB - Mobiles
Lenovo IdeaPad Slim 3 - Laptops
14 products, statements: 2

-- n1, 20 orders of 20 customers (order lines left out)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 order by o1_0.order_id
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
Statements: 3

What this code does

  • The first lazy getName() loaded all 6 waiting categories with one IN query. For 20 different customers it took two IN queries: 16 ids, then the other 4.
  • Each IN list has 16 ? even when fewer ids are left; Hibernate pads the list so the statement text never changes.

One setting, hibernate.default_batch_fetch_size, turns batch fetching on for every link and collection; @BatchSize(size = 16) on one association or entity class sets it for just that place. In Example 4 the unchanged N+1 code drops from 7 statements to 2. With 20 customers and size 16 it takes 3: one batch of 16 and one of the remaining 4. The count is 1 + ⌈distinct / size⌉, so 2000 customers need 126 statements, not 2001 and not 1. The IN list always has 16 placeholders; Hibernate pads it so MySQL sees one statement shape.

Batch fetching is the safety net, not the best fix. It needs no code change and helps code you have not found yet, including links read in mappers. For a known hot screen, a fetch join or entity graph is still better: one statement.

Fetching two collections: MultipleBagFetchException

A bag is an unordered List collection without an index column. Hibernate refuses to fetch-join two bags of one entity in one query, because the joined rows would multiply.

A customer has a list of addresses and a list of orders. Fetching both in one query fails, and Example 5 shows the exception and a two-query fix.

Java
// Fix 1: one collection as a Set (no MultipleBagFetchException, but rows multiply)@OneToMany(mappedBy = "customer")@OrderBy("id")private Set<Address> addresses = new LinkedHashSet<>();

Example 5 · Two bags in one query fail; two queries work

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

Java
// LabDemos.java (fragment): Customer.addresses and Customer.orders are both Listpublic void twoBags() {    try {        List<Customer> list = em.createQuery(                "select c from Customer c join fetch c.addresses join fetch c.orders", Customer.class)                .getResultList();        System.out.println("Rows in the list: " + list.size());    } catch (RuntimeException e) {        System.out.println(e.getClass().getName() + ": " + e.getMessage());        Throwable cause = e.getCause();        if (cause != null) {            System.out.println("Caused by: " + cause.getClass().getName() + ": " + cause.getMessage());        }    }}
// LabDemos.java (fragment): the fix with two queries in one transactionpublic void twoQueries() {    stats.clear();    List<Customer> list = em.createQuery(            "select c from Customer c left join fetch c.addresses order by c.id", Customer.class)            .getResultList();    em.createQuery("select c from Customer c left join fetch c.orders where c in :customers", Customer.class)      .setParameter("customers", list)      .getResultList();    for (Customer c : list) {        System.out.println(c.getFullName() + ": " + c.getAddresses().size() + " addresses, "                + c.getOrders().size() + " orders");    }    System.out.println("Statements: " + stats.getPrepareStatementCount());}
Sample output
-- bags
java.lang.IllegalArgumentException: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.shoplite.lab.customer.Customer.addresses, com.shoplite.lab.customer.Customer.orders]
Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.shoplite.lab.customer.Customer.addresses, com.shoplite.lab.customer.Customer.orders]

-- twoqueries
DEBUG SQL - select c1_0.customer_id,a1_0.customer_id,a1_0.address_id,a1_0.city,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.pincode,a1_0.state,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 left join addresses a1_0 on c1_0.customer_id=a1_0.customer_id order by c1_0.customer_id,a1_0.address_id
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,o1_0.customer_id,o1_0.order_id,o1_0.address_id,o1_0.ordered_at,o1_0.status,c1_0.phone from customers c1_0 left join orders o1_0 on c1_0.customer_id=o1_0.customer_id where c1_0.customer_id in (?,?,?,?,?,?,?,?) order by o1_0.order_id
Asha Rao: 2 addresses, 3 orders
Ravi Kumar: 1 addresses, 3 orders
Meena Iyer: 1 addresses, 2 orders
Kabir Singh: 1 addresses, 2 orders
Priya Sharma: 2 addresses, 2 orders
Arjun Mehta: 1 addresses, 2 orders
Divya Nair: 1 addresses, 2 orders
Imran Khan: 0 addresses, 0 orders
Statements: 2

What this code does

  • Fetching addresses and orders (both List) together throws MultipleBagFetchException when the query is created, before any SQL is sent.
  • Two queries in one transaction load the same 8 customer objects twice; the second query fills their orders collections. 2 statements, and each row in each result is needed. Imran Khan stays thanks to left join fetch.

Two bags in one join would pair every address with every order, and Hibernate cannot tell the real children apart, so it throws MultipleBagFetchException ("cannot simultaneously fetch multiple bags"). If the query is in a @Query annotation, the app does not even start. Fix 1 is the Set of the snippet above: Hibernate then removes duplicates and the query runs, but the SQL still returns the Cartesian product: 21 joined rows for the seed customers where 9 addresses and 16 orders are needed, and 500 rows per customer with 10 addresses and 50 orders.

Fix 2 is usually better: two queries in one transaction. Query 1 fetches customers with addresses; query 2 fetches the same customers with orders (where c in :customers). The persistence context merges them into the same objects, as Example 5 shows: 2 statements, no duplicate rows.

Fix the error

Fix the exception

Read the real error, then pick the line that fixes it.

One fetch-join query for two lists of a customer.

@Query("select c from Customer c join fetch c.addresses join fetch c.orders")
List<Customer> findAllWithBoth();

Error

MultipleBagFetchException: cannot simultaneously fetch multiple bags:
[Customer.addresses, Customer.orders]

Fetch join with paging: page the ids first

Ids-first paging is a way to page entities that have a collection. Query 1 pages only the ids, and query 2 loads exactly those ids together with their collection.

SQL LIMIT counts rows, not customers, so paging and a collection fetch do not mix. Example 6 runs three versions on the same data.

Example 6 · Paging customers with their orders: three versions

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

Java
// CustomerRepository.java (fragment)@Query(value = "select c from Customer c join fetch c.orders",       countQuery = "select count(c) from Customer c")Page<Customer> findPageWithOrders(Pageable pageable);
@Query("select c.id from Customer c")Page<Integer> findIdPage(Pageable pageable);
@Query("select c from Customer c left join fetch c.orders where c.id in :ids order by c.id")List<Customer> findWithOrdersByIdIn(List<Integer> ids);
// LabDemos.java (fragment)public void pageWithFetch() {    stats.clear();    Page<Customer> page = customers.findPageWithOrders(PageRequest.of(0, 3, Sort.by("id")));    for (Customer c : page) {        System.out.println(c.getFullName() + ": " + c.getOrders().size() + " orders");    }    System.out.println("Page 0 of " + page.getTotalPages() + ", statements: " + stats.getPrepareStatementCount());}
public void pageOfIdsThenFetch() {    stats.clear();    Page<Integer> ids = customers.findIdPage(PageRequest.of(0, 3, Sort.by("id")));    List<Customer> list = customers.findWithOrdersByIdIn(ids.getContent());    for (Customer c : list) {        System.out.println(c.getFullName() + ": " + c.getOrders().size() + " orders");    }    System.out.println("Page 0 of " + ids.getTotalPages() + ", statements: " + stats.getPrepareStatementCount());}
Sample output
-- pagefetch on Spring Boot 4.1 / Hibernate 7.4.5
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,o1_0.customer_id,o1_0.order_id,o1_0.address_id,o1_0.ordered_at,o1_0.status,c1_0.phone from (select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where exists(select 1 from orders o1_0 where c1_0.customer_id=o1_0.customer_id) order by c1_0.customer_id limit ?,?) c1_0(customer_id,created_at,email,full_name,phone) join orders o1_0 on c1_0.customer_id=o1_0.customer_id order by c1_0.customer_id,o1_0.order_id
DEBUG SQL - select count(c1_0.customer_id) from customers c1_0
Asha Rao: 3 orders
Ravi Kumar: 3 orders
Meena Iyer: 2 orders
Page 0 of 3, statements: 2

-- the same pagefetch on Spring Boot 3.5 / Hibernate 6.6.33
WARN  query - HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,o1_0.customer_id,o1_0.order_id,o1_0.address_id,o1_0.ordered_at,o1_0.status,c1_0.phone from customers c1_0 join orders o1_0 on c1_0.customer_id=o1_0.customer_id order by c1_0.customer_id,o1_0.order_id
DEBUG SQL - select count(c1_0.customer_id) from customers c1_0
Asha Rao: 3 orders
Ravi Kumar: 3 orders
Meena Iyer: 2 orders
Page 0 of 3, statements: 2

-- pageids (any version)
DEBUG SQL - select c1_0.customer_id from customers c1_0 order by c1_0.customer_id limit ?
DEBUG SQL - select count(*) from customers c1_0
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,o1_0.customer_id,o1_0.order_id,o1_0.address_id,o1_0.ordered_at,o1_0.status,c1_0.phone from customers c1_0 left join orders o1_0 on c1_0.customer_id=o1_0.customer_id where c1_0.customer_id in (?,?,?) order by c1_0.customer_id,o1_0.order_id
Asha Rao: 3 orders
Ravi Kumar: 3 orders
Meena Iyer: 2 orders
Page 0 of 3, statements: 3

What this code does

  • Hibernate 7.4 pushed the limit into a subquery, but the count query counted all 8 customers while the page only includes the 7 with orders. Hibernate 6.6 loaded every customer with every order and paged in memory (HHH90003004).
  • The ids-first version runs 3 small statements: one page of ids, the count, and one fetch for exactly those ids. It behaves the same on every Hibernate version.

A page of 3 customers cannot be cut from joined rows. Hibernate 5 and 6 solved this in memory: they logged HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory, loaded every customer with every order, and kept 3. Fine for 8 customers, a memory problem for 80,000. Hibernate 7.4 (Spring Boot 4.1) puts the LIMIT into a subquery on customers, but two traps stay. The page query added where exists (... orders ...) because join fetch is an inner join, while the count query counts all 8 customers, so the page totals are wrong. And a condition on the fetched collection made Hibernate 7.4.5 build SQL that MySQL rejected in our test ("Unknown column 'o1_0.status'").

The pattern that works on every version is to page the ids, then fetch. Query 1 pages only ids (select c.id ... limit ?) with its own count; query 2 loads those ids with their orders (where c.id in :ids). Three simple statements, correct totals, and nothing loaded that the page does not show.

Order of execution

Page the ids first

Put the steps of the ids-first pattern in the order they run.

Next step

Check your understanding

12 quick questions