Spring Boot & Microservices (50 Qs)•Part 3: Microservices, Distributed Systems & Observability (25 - 35)
Spring Data JPA: Resolving the N+1 Query Problem.
senior LevelSystem DesignMicroservices
In Simple Words: The N+1 Problem occurs when loading 100 parent records executes 1 query for the parents plus 100 separate sub-queries to fetch child relationships:
- Solution 1: Join Fetch in JPQL:
@Query("SELECT o FROM Order o JOIN FETCH o.items")(Fetches parent and children in 1 query). - Solution 2:
@EntityGraph:@EntityGraph(attributePaths = {"items", "customer"}) - Solution 3: DTO Projection: Select only the exact columns needed into a Java Record.