Medium java backend

Remove N+1 queries (fetch joins or batch fetching)

The 30 second answer

The N+1 problem is one query for a list and then one extra query per item, usually from lazy loading in JPA. I spot it in SQL logs or traces as many near-identical queries. I fix it with a fetch join or entity graph for that use case, or with batch fetching so related rows load in groups, and I add a test that checks the query count.

N+1 means one query for the list, then one more query per row for a lazy association. The Hibernate guide fixes it per query with JOIN FETCH or an entity graph, or with @BatchSize / hibernate.default_batch_fetch_size to load many associations in one IN query. Hibernate recommends lazy mappings plus fetching per use case, not global EAGER.

@Query("select o from Order o join fetch o.items where o.customer.id = :id")
List<Order> findWithItems(Long id);
Sources (1)
  1. Hibernate 6.6 User Guide: Fetching