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
Orderrecords issues 1 SQL query. Then accessingorder.getCustomer()inside a loop issues 100 additional SQL queries (1 + N = 101 queries), destroying database performance. - Solutions:
JOIN FETCHin JPQL:SELECT o FROM Order o JOIN FETCH o.customerfetches parent and children in 1 query.- EntityGraph:
@EntityGraph(attributePaths = {"customer"}). - Batch Size:
@BatchSize(size = 25)on the relation to load related entities using SQLWHERE 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);
}