N+1 queries
The N+1 problem is one query that loads N parent rows, then one query per parent for a child collection. You meant one or two queries. You got 1 + N.
Detailed Explanation
List<Order> orders = repo.findAll() is one select. Then the view calls order.getLines() on each order. Each call, with lazy @OneToMany, runs select * from lines where order_id = ?. For 50 orders that is 51 queries. On a remote database that is 51 round trips.
JPA lazy loading is the usual source. Hibernate logs (generate_statistics, datasource proxy) make it visible. The fix is to fetch what you need in the first query: join fetch o.lines, an @EntityGraph, a DTO projection, or a batch size (@BatchSize) that turns N into N/batch. join fetch of two bags can multiply rows (Cartesian product); then use two queries or a fetch graph carefully.
You reach for a fetch plan when a use case always needs the children. You keep lazy when most callers do not. You do not "fix" N+1 by turning every association eager; that makes every query huge.
The cost of N+1 is latency that grows with list size. It passes on a 3-row fixture and fails in production. The cost of a blind join fetch on a huge collection is a memory spike. Paginate, or query ids first.
Spring's open-in-view lets N+1 happen in the JSON serializer, far from the repository. Disable it so lazy access fails in the service layer where you can fix the query.
Unit tests with H2 and 2 rows will not catch this. Assert query count in an integration test if the list endpoint matters.
A useful habit is to name the use case on the repository method: findOpenOrdersWithLines. The fetch plan belongs to that method, not to the entity. Another caller that only needs ids should not pay for lines. Hibernate statistics or a datasource proxy in tests can assert "this method runs at most 2 selects". That assertion is worth more than a comment that says "watch N+1".
Code Examples
import java.util.List;
interface OrderRepo {
List<Order> findAll();
List<Order> findAllWithLines(); // implemented with join fetch
}
class Order {
List<String> lines() {
return List.of();
}
}
public class BadLoop {
static int countLines(OrderRepo repo) {
int n = 0;
for (Order o : repo.findAll()) { // N+1 if lines() is lazy
n += o.lines().size();
}
return n;
}
}JPQL sketch: one query, lines fetched
// JPQL sketch: one query, lines fetched
// select distinct o from Order o left join fetch o.lines
public class Fetch {
static String jpql() {
return "select distinct o from Order o left join fetch o.lines";
}
public static void main(String[] args) {
System.out.println(jpql().contains("join fetch")); // prints: true
}
}Common Gotchas
Eager on the mapping is global
it hurts use cases that did not need the children.
Small fixtures hide N+1
measure query count on realistic N.
Two `join fetch` bags can cartesian-explode the result set
Two `join fetch` bags can cartesian-explode the result set