Spring / Spring7 Intermediate to Advanced Interview questions
How do you optimize a Spring Data JPA application to avoid the N+1 query problem?
The N+1 problem shows up when loading a list of parent entities triggers one query for the list, then a separate lazy-loading query for each row's related association - a hundred orders each lazily fetching their line items means a hundred and one round trips to the database instead of two.
@Query("SELECT o FROM Order o JOIN FETCH o.lineItems WHERE o.status = :status") List<Order> findByStatusWithItems(@Param("status") String status); // or, without changing the entity's default fetch type globally @EntityGraph(attributePaths = "lineItems") List<Order> findByStatus(String status);
JOIN FETCH in a JPQL query eagerly pulls the association into the same single query. @EntityGraph achieves the same result for a specific repository method without changing the entity's default (and normally sensible) lazy-fetch type everywhere else. For associations that can't cleanly be joined - a collection accessed across many different code paths - Hibernate's batch fetching (hibernate.default_batch_fetch_size, or @BatchSize on the association) groups the lazy loads into batched IN (...) queries instead of one row at a time, which is a lower-effort fix when a targeted JOIN FETCH isn't practical. Finally, when the use case only needs a handful of fields, a Spring Data projection or DTO query avoids hydrating full entity graphs at all, sidestepping the N+1 question entirely for read-heavy endpoints.
More Related questions...