Skip to main content
InterviewHubPRO
Section Overview
Q16

Question 16 of 50

Part 2: Persistence, Transactions & Security (11 - 24)

32%
Spring Boot & Microservices (50 Qs)•Part 2: Persistence, Transactions & Security (11 - 24)

What is the N+1 Query Problem in JPA/Hibernate, and how do you solve it?

junior LevelCode ExampleState ManagementSecurity & AuthDatabases & SQL

In Simple Words:

  • Problem: Fetching 100 Order records issues 1 SQL query. Then accessing order.getCustomer() inside a loop issues 100 additional SQL queries (1 + N = 101 queries), destroying database performance.
  • Solutions:
    1. JOIN FETCH in JPQL: SELECT o FROM Order o JOIN FETCH o.customer fetches parent and children in 1 query.
    2. EntityGraph: @EntityGraph(attributePaths = {"customer"}).
    3. Batch Size: @BatchSize(size = 25) on the relation to load related entities using SQL WHERE id IN (?, ?, ...).
java
public interface OrderRepository extends JpaRepository<Order, UUID> {
    // Solves N+1 by fetching related Customer in a single SQL JOIN:
    @Query("SELECT o FROM Order o JOIN FETCH o.customer WHERE o.status = :status")
    List<Order> findAllWithCustomerByStatus(@Param("status") String status);
}