Skip to lesson

Practice: JPA performance traps

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

An order page that sends 8 statements, a customer list that pages in memory, an entity where a record would do: JPA performance bugs repeat a few shapes. Practise recognising them from code and logs.

Count the queries before you run the code

Before running code, predict its statements. Example 1 applies four counting rules to the names demo and then checks the answer in the log.

Example 1 · Predict, then check: the names demo three ways

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

Java
// LabDemos.java (fragment)public 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=names --spring.jpa.properties.hibernate.default_batch_fetch_size=16java -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=namesgraph
Sample output
-- names
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

-- names with batch size 16
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

-- 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

What this code does

  • The prediction 7, 2 and 1 matches the three runs: N+1 over 6 categories, one IN batch, and one SELECT with a left join.
  • In the first run the category SELECTs appear between the printed lines: a lazy read in the loop, not an EAGER mapping.

Counting statements from code follows four rules:

  • A query method is 1 statement (plus 1 count query for a Page when the first page is full or a later page is asked for).
  • Each EAGER to-one link adds 1 per distinct linked row, right after the query.
  • Each lazy link read in a loop adds 1 per distinct linked row, at the moment it is read.
  • The persistence context never loads the same id twice in one transaction.

Apply them to the names demo: 1 query for 14 active products, then the loop reads 6 distinct categories, so 7. With default_batch_fetch_size: 16 the 6 categories come in one IN query: 2. With a fetch join or entity graph: 1. Always check your prediction in the SQL log or with statistics. A wrong prediction usually means a hidden read: a toString, a mapper, Jackson, or an EAGER link two steps away.

Mistake: EAGER mappings and lazy reads in loops

Two opposite mistakes give the same log lines. Example 2 shows the EAGER one; compare where its SELECTs appear with Example 1.

Example 2 · EAGER: the same SELECTs, before the loop

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

Java
// Product.java (fragment): a plain @ManyToOne is EAGER@ManyToOne@JoinColumn(name = "category_id")private Category category;
// LabDemos.java (fragment)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

  • All 6 category SELECTs run before "Loaded 14 products": they belong to the query call, not to the loop.
  • The fix is in the mapping (fetch = FetchType.LAZY); after it, this method sends 1 statement plus 1 for the one category it reads.

A plain @ManyToOne (EAGER by default) sends the extra SELECTs inside the query call, whether or not the code needs them. A LAZY link read in a loop sends them inside the loop, only if the code needs them. Both show the same block of select ... where category_id=? lines. Tell them apart by where the SELECTs appear: before your first println (EAGER) or between your loop's lines (lazy reads). The first is fixed in the mapping (fetch = FetchType.LAZY); the second in the query (fetch join, entity graph or batch size).

Switching a lazy link to EAGER moves the same statements into every query of that entity, including the ones that never use the link, so it never fixes N+1.

Mistake: paging a collection fetch

A collection fetch with a page depends on the Hibernate version. Example 3 runs it on 6.6 and then with the ids-first fix.

Example 3 · In-memory paging on Hibernate 6.6, and the ids-first fix

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);
Sample output
-- findPageWithOrders 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

-- ids first (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 6.6 sent the join without any LIMIT and kept 3 customers in memory; with a big table this loads everything on every page.
  • The ids-first version pages in SQL (limit ?) and fetches only the 3 customers of the page.

On Hibernate 5 and 6 (Spring Boot 2 and 3), join fetch of a collection with a Pageable logs HHH90003004 ... applying in memory, loads every matching parent with every child and cuts the page in Java. On Hibernate 7.4 it pages in a subquery, but the count query may not match the page.

The portable fix is the same everywhere: page the parent ids with their count, then fetch those parents with their collection by id. It costs three statements and loads only what the page shows. In a code review, look for Pageable (or setMaxResults) on any query that fetches a @OneToMany, whether by join fetch or by an entity graph.

Choosing the fix

The fix depends on the use case, not on taste. Example 4 shows a read-only report as one DTO query.

Example 4 · A read-only report as one DTO query

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

Java
// OrderRepository.java (fragment)@Query("""        select new com.shoplite.lab.order.OrderTotalRow(            o.id, c.fullName, o.status, sum(i.quantity), sum(i.quantity * i.unitPrice))        from Order o join o.customer c join o.items i        where o.status = :status        group by o.id, c.fullName, o.status        order by o.id""")List<OrderTotalRow> findTotalsByStatus(OrderStatus status);
Sample output
DEBUG SQL - select o1_0.order_id,c1_0.full_name,o1_0.status,sum(i1_0.quantity),sum((i1_0.quantity*i1_0.unit_price)) from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id join order_items i1_0 on o1_0.order_id=i1_0.order_id where o1_0.status=? group by o1_0.order_id,c1_0.full_name,o1_0.status order by o1_0.order_id
OrderTotalRow[orderId=1, customerName=Asha Rao, status=DELIVERED, items=3, total=21097.00]
OrderTotalRow[orderId=2, customerName=Ravi Kumar, status=DELIVERED, items=4, total=1947.00]
OrderTotalRow[orderId=3, customerName=Asha Rao, status=DELIVERED, items=2, total=43839.00]
OrderTotalRow[orderId=5, customerName=Kabir Singh, status=DELIVERED, items=2, total=22198.00]
statements: 1, entities loaded: 0

What this code does

  • Orders, customers and items in one statement, totalled by MySQL; no entities loaded, so nothing lazy can run later.
  • With entities the same report would load orders, customers and every item before adding them up in Java.

Use the shortest option that fits:

  • Read-only screen, a few columns, maybe totals: a DTO query (select new ...), returned as records.
  • The use case changes the entities and needs a link: join fetch in JPQL or @EntityGraph on the repository method.
  • Two collections: two queries in one transaction; never two bags in one fetch join.
  • Everywhere, as a safety net: default_batch_fetch_size, open-in-view=false, and a query-count test per important endpoint.

Finish up

Mark complete & continue

Next: ShopLite: a fast product listing