Learning Objectives
- Diagnose N+1 query storms in Hibernate SQL logs and Hibernate Statistics.
- Resolve collection fetching cleanly using `@EntityGraph` and `JOIN FETCH` without breaking pagination.
- Keep `spring.jpa.open-in-view=false` enabled in production APIs.
Prerequisites
- Spring Boot repository basics and relational SQL JOINs
Why Does the N+1 Problem Happen?
Imagine querying 25 courses (`1` SELECT) and returning each course’s module titles inside your JSON mapper. When a lazy association (@OneToMany(fetch = FetchType.LAZY)) is traversed inside the loop, Hibernate fires `25` extra round-trip SQL queries — totaling 26 queries (1 + N) for one endpoint call.
Three Clean Production Fixes
- EntityGraph / JOIN FETCH: Load the needed parent and child associations inside a single SQL join when unpaginated.
- Two-Step ID Pagination + IN Fetch: For paginated endpoints with `ToMany` collections, fetch `Page<Long>` IDs first, then join-fetch by `WHERE c.id IN (:ids)` to avoid in-memory Hibernate pagination (`HHH90003004`).
- Closed DTO Projections: Select only displayed scalar columns rather than hydrating full dirty-checked Hibernate entities for read endpoints.
Pair this optimization with SQL Joins & B-Tree Index Optimization and Java Backend Career Program.
Practical Programming Examples
Solving N+1 Cleanly with Spring Data JPA @EntityGraph & DTO Read
Replace 1+N lazy module queries with a single eager SQL fetch scoped purely to one repository query.
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CourseRepository extends JpaRepository<Course, Long> {
@EntityGraph(attributePaths = {"modules"})
List<Course> findByIsPublishedTrueOrderBySortOrderAsc();
}
Hibernate executes 1 LEFT OUTER JOIN SQL query instead of 1 + N child SELECT statements.
- Keep associations `FetchType.LAZY` globally on entity classes so unused endpoints stay lightweight.
- Attach `@EntityGraph(attributePaths = {"modules"})` only on the specific query method that renders nested modules.
- Verify query counts using SQL logging or automated `assertQueryCount <= 2` integration assertions.
Common Mistakes to Avoid
- Switching associations globally to `FetchType.EAGER` — slows down every endpoint that does not need child collections.
- Combining `Pageable` directly with `JOIN FETCH` on a `@OneToMany` bag, causing Hibernate to fetch the entire table into JVM memory.
Production Best Practices
- Set `spring.jpa.open-in-view=false` in `application.yml` so accidental lazy loading in serializers fails fast during tests.
- Keep read endpoints on read-only `@Transactional(readOnly = true)` transactions.
Technical Interview Relevance
Standard Spring Boot + PostgreSQL performance question separating engineers who test real SQL logs from CRUD-only developers.
Practice & Self-Check Questions
Why should `spring.jpa.open-in-view` be disabled in production Spring Boot APIs?
OSIV holds a database connection open across the entire HTTP rendering phase, masking N+1 queries and exhausting connection pools under traffic.