Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →
TOPIC 3 OF 5 · 2 MIN READ

The N+1 Query Problem in JPA and How to Fix It

The N+1 problem is the most common JPA performance bug: one query loads N entities and then N more queries load an association for each. Interviewers expect you to recognise it and know several fixes.

What you will learn

  • Recognise N+1 from SQL logs
  • Fix it with JOIN FETCH and @EntityGraph
  • Use batch fetching and DTO projections
  • Paginate safely with collections

Key concepts

JOIN FETCH

A JPQL join that also initialises the association in the same query: select o from Order o join fetch o.customer.

@EntityGraph

Declares which associations to fetch for a repository method without writing JPQL.

Batch fetching

hibernate.default_batch_fetch_size=50 loads lazy associations for up to 50 parents in one IN query, turning N+1 into 1 + N/50.

DTO projection

Select only the columns you need into a record: select new com.app.OrderSummary(o.id, c.name, o.total) from Order o join o.customer c. Fast and no lazy loading at all.

Step by step

Spot it

List<Order> orders = orderRepository.findByStatus(PAID);   // 1 query
orders.forEach(o -> System.out.println(o.getCustomer().getName()));   // +1 query per order

# spring.jpa.show-sql=true or logging.level.org.hibernate.SQL=debug
# select ... from orders where status=?
# select ... from customers where id=?   (repeated N times)

Fix it

public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("select o from Order o join fetch o.customer where o.status = :status")
    List<Order> findPaidWithCustomer(OrderStatus status);

    @EntityGraph(attributePaths = {"customer", "items"})
    List<Order> findByStatus(OrderStatus status);

    @Query("select new com.app.OrderSummary(o.id, c.name, o.total) from Order o join o.customer c where o.status = :status")
    List<OrderSummary> summaries(OrderStatus status);
}

Examples

Pagination with a collection fetch

// Fetch-joining a collection with Pageable makes Hibernate paginate IN MEMORY (warning HHH90003004).
// Two-step instead:
Page<Long> ids = orderRepository.findIdsByStatus(PAID, pageable);           // page of ids
List<Order> page = orderRepository.findWithItemsByIdIn(ids.getContent());   // fetch join for those ids

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Write a test that asserts the number of SQL statements an endpoint runs (Hibernate statistics or datasource-proxy).
  • Compare JOIN FETCH, @EntityGraph and batch fetching on the same data set.

Interview questions

What interviewers ask next on this topic. Answer out loud first, then open the model answer.

Does FetchType.EAGER fix N+1?

No. EAGER only changes when the association loads. With JPQL queries Hibernate still loads eager associations with separate queries, so you can get N+1 anyway, plus extra data everywhere. Fix it per query with fetch joins, entity graphs or batching.

Summary

Watch SQL logs, fix N+1 with JOIN FETCH or @EntityGraph for specific queries, batch fetching as a safety net, DTO projections for read-only views, and two-step queries for paginating collections.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus