Skip to main content
Intermediate Practical Programming Example 11 min read Spring Data JPA 3.x / Hibernate 6

Spring Data JPA N+1 Problem Explained and Fixed Cleanly

Stop serializing hundreds of accidental child queries per API request using EntityGraph, JOIN FETCH, and targeted DTO projections.

Written by MockAttempt Engineering Editorial Desk (Curriculum & Code Verification Review Panel) Reviewed by Ravi Shankar Mishra
Last updated: Verification Policy

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.

Spring Data JPA 3.3 / Hibernate 6
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();
}
Expected Output
Hibernate executes 1 LEFT OUTER JOIN SQL query instead of 1 + N child SELECT statements.
Step-by-Step Execution
  1. Keep associations `FetchType.LAZY` globally on entity classes so unused endpoints stay lightweight.
  2. Attach `@EntityGraph(attributePaths = {"modules"})` only on the specific query method that renders nested modules.
  3. 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.

Optional Next Step

Have Questions About Learning Spring Boot Structured Cohorts?

Request the JBCP syllabus & weekend batch schedule from an Academic Counselor.

View JBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.