Video in progress
How does the N+1 problem appear in Spring Data JPA, and how do you detect and fix it?
You load a list with one query, then touch a lazy association on each element, and every one of them fires another query: 1 + N. The fix is JOIN FETCH, @EntityGraph, batch fetching or a DTO projection.
📖 Answer
List<Order> orders = orderRepo.findByStatus(PAID); // 1 query
for (Order o : orders) {
total += o.getCustomer().getDiscount(); // +1 query for each
}
100 orders means 101 queries. You won't notice on a local database, but on prod network latency adds up and the page takes seconds to open.
How to find it: in a test, turn on spring.jpa.properties.hibernate.generate_statistics=true and check the query count, or count SQL statements with datasource-proxy or p6spy. In an APM trace it is also obvious right away when the same SQL runs over and over inside a single request.
The fix:
@EntityGraph(attributePaths = "customer")
List<Order> findByStatus(Status status);
// or
@Query("select o from Order o join fetch o.customer where o.status = :s")
List<Order> findPaidWithCustomer(@Param("s") Status s);
One setting helps everywhere at once: hibernate.default_batch_fetch_size=50. Lazy associations are loaded 50 at a time with IN (...), so 3 queries instead of 101.
One catch: if join fetch, a collection and pagination come together, Hibernate loads all the rows into memory and paginates in Java (the HHH90003004 warning). In that case, page the ids first, then fetch those.
Sign up to mark studied questions and save your progress.