The N+1 Query Problem in Spring Boot: Reproduce It, Fix It, Prove It

One innocent loop, 1,001 SQL statements. A complete Spring Boot + Hibernate demo where every scenario was actually executed and measured — the N+1 baseline, @EntityGraph, @BatchSize, and DTO projections — with real query counts you can reproduce.

The N+1 query problem is the most common performance bug in JPA applications, and the cruelest part is how innocent it looks. You write four lines of perfectly reasonable code, it passes every test, it’s fast on your laptop — and then in production it fires ten thousand queries per request. This post reproduces it for real: a complete Spring Boot application, executed end to end, with every query counted. Then three fixes, each measured the same way.

The N+1 query problem: findAll issues 1 query returning N authors, then touching each author's lazy books collection fires N more queries — 1 + N statements total
The shape of the bug: 1 query becomes 1 + N. Click to expand.

What “N+1” actually means

You load N parent rows with 1 query. Then, because a child collection is lazily loaded, touching it on each parent fires one more query per parent — N additional queries. Total: 1 + N. The “+1” is the original query; the “N” is the ambush.

It happens with any lazy association: @OneToMany, @ManyToMany, even @ManyToOne when you walk the graph in a loop.

The setup: a demo you can run

Everything below was executed on Java 21, Spring Boot 3.3.5, Hibernate 6.5.3, H2 (in-memory). The dataset: 1,000 authors × 5 books = 5,000 books. Copy-pasteable as-is.

pom.xml — the only dependencies you need:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.5</version>
    <relativePath/>
</parent>

<properties>
    <java.version>21</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

The entities — note FetchType.LAZY on the collection, which is the default for @OneToMany and exactly what production code usually has:

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY,
               cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books = new ArrayList<>();

    protected Author() {}
    public Author(String name) { this.name = name; }
    public Long getId() { return id; }
    public String getName() { return name; }
    public List<Book> getBooks() { return books; }
    public void addBook(Book book) { books.add(book); book.setAuthor(this); }
}

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    private Author author;

    protected Book() {}
    public Book(String title) { this.title = title; }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public Author getAuthor() { return author; }
    public void setAuthor(Author author) { this.author = author; }
}

The repository and the runner that measures each scenario:

public interface AuthorRepository extends JpaRepository<Author, Long> {

    @EntityGraph(attributePaths = "books")
    @Query("select a from Author a")
    List<Author> findAllWithBooks();

    @Query("select new com.bitlabs.nplus1.AuthorBookCount(a.name, count(b)) " +
           "from Author a left join a.books b group by a.name order by a.name")
    List<AuthorBookCount> findAuthorBookCounts();
}

public record AuthorBookCount(String authorName, long bookCount) {}
# application.properties
spring.datasource.url=jdbc:h2:mem:nplus1db;DB_CLOSE_DELAY=-1
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.generate_statistics=true
spring.main.banner-mode=off

Counting queries honestly

Guessing is how N+1 survives code review. Hibernate’s Statistics API counts every prepared statement the session executes — I cleared it before each scenario and read getPrepareStatementCount() after:

private void scenario(String name, Supplier<Long> work) {
    em.clear(); // detach everything: forces real database round trips
    Statistics stats = em.getEntityManagerFactory()
            .unwrap(SessionFactory.class).getStatistics();
    stats.clear();
    long start = System.nanoTime();
    long totalBooks = work.get();
    long ms = (System.nanoTime() - start) / 1_000_000;
    System.out.printf("%n=== %s ===%n", name);
    System.out.printf("SQL statements   : %d%n", stats.getPrepareStatementCount());
    System.out.printf("Books counted    : %d%n", totalBooks);
    System.out.printf("Time taken       : %d ms%n", ms);
}

The em.clear() matters: without it, entities seeded moments ago sit in the persistence context with their collections already in memory, and the lazy loads never fire. (I learned that the embarrassing way — my first run reported “1 statement” for the baseline.)

Reproducing it: 1,001 statements

The scenario is the code every one of us has written:

List<Author> authors = authorRepository.findAll();   // 1 query
long total = 0;
for (Author a : authors) {
    total += a.getBooks().size();                    // N queries
}

Real output from the run:

=== 1) Baseline: lazy loading (the N+1 problem) ===
SQL statements   : 1001
Books counted    : 5000
Time taken       : 769 ms

1,001 statements for a loop a junior would approve in review. The per-author SQL Hibernate emits looks like this (captured with show-sql):

select b1_0.author_id, b1_0.id, b1_0.title
from book b1_0
where b1_0.author_id = ?
-- executed 1,000 times, once per author

Why it hurts: the consequences

The statement count is the headline, but the damage is in what those statements cost:

  1. Round trips, not rows. Each of the 1,000 queries is a network round trip to the database. On in-memory H2 the whole thing took 769 ms; add even 1 ms of network latency per trip and you’re past a second before the database does any work.
  2. Connection pool starvation. Under load, hundreds of requests each holding a connection for 1,001 sequential queries drain the pool. The symptom looks like “the database is slow” — the database is fine; you’re just chatting with it too much.
  3. It’s invisible in dev. With 10 authors in your local database this is 11 queries and ~5 ms. Nothing looks wrong. The problem scales with your data, so it arrives exactly when you can least afford it — in production.

Fix 1: @EntityGraph — one JOIN FETCH

Tell JPA up front that you’ll need the collection, and it fetches everything in a single join:

@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooks();
=== 2) Fix: @EntityGraph (single JOIN FETCH) ===
SQL statements   : 1
Books counted    : 5000
Time taken       : 205 ms

The SQL Hibernate actually emits:

select a1_0.id, b1_0.author_id, b1_0.id, b1_0.title, a1_0.name
from author a1_0
left join book b1_0 on a1_0.id = b1_0.author_id

One statement, 205 ms vs 769 ms. Two caveats worth knowing: fetching two collections this way produces a Cartesian product (fetch one, batch the other), and combining a fetch join with pagination triggers Hibernate’s HHH90003004 warning — it fetches all rows into memory and paginates there.

Fix 2: @BatchSize — controlled lazy loading

Sometimes you can’t restructure the query — the lazy access happens deep in some other layer’s code. @BatchSize keeps lazy loading but fetches many collections per round trip:

@OneToMany(mappedBy = "author", fetch = FetchType.LAZY,
           cascade = CascadeType.ALL, orphanRemoval = true)
@BatchSize(size = 100)   // org.hibernate.annotations.BatchSize
private List<Book> books = new ArrayList<>();
=== 1) Baseline with @BatchSize(100) ===
SQL statements   : 11
Books counted    : 5000
Time taken       : 448 ms

11 statements: 1 for the authors + ⌈1000/100⌉ batched collection loads. The SQL becomes an IN query:

select b1_0.author_id, b1_0.id, b1_0.title
from book b1_0
where b1_0.author_id in (?, ?, ?, …)   -- 100 bind params, 10 executions

This is the lowest-effort fix — one annotation, no query changes — and it degrades gracefully: the count is 1 + ⌈N/batchSize⌉ instead of 1 + N.

Fix 3: DTO projection — don’t load entities at all

If you only need the count per author, loading 5,000 entity instances to count them is waste. Ask the database for the answer directly:

@Query("select new com.bitlabs.nplus1.AuthorBookCount(a.name, count(b)) " +
       "from Author a left join a.books b group by a.name order by a.name")
List<AuthorBookCount> findAuthorBookCounts();
=== 3) Fix: DTO projection (single aggregate query) ===
SQL statements   : 1
Books counted    : 5000
Time taken       : 170 ms
select a1_0.name, count(b1_0.id)
from author a1_0
left join book b1_0 on a1_0.id = b1_0.author_id
group by a1_0.name order by a1_0.name

One statement, the fastest of the three fixes here, and no entities enter the persistence context — no dirty checking, no first-level-cache memory. The trade-off: you get exactly the fields you asked for, nothing more. Perfect for read models and dashboards, wrong when you need managed entities.

Three measured fixes: EntityGraph emits 1 statement, BatchSize(100) emits 11, DTO projection emits 1 — against the 1001-statement lazy baseline
All three fixes, measured on the same data. Click to expand.

Which fix when

SituationFixStatements (N=1000)
You control the query and need the entities@EntityGraph / JOIN FETCH1
Lazy access happens in code you can’t restructure@BatchSize1 + ⌈N/size⌉
You only need a few fields (counts, summaries)DTO projection1
Multiple collections needed at once@EntityGraph on one, @BatchSize on the rest1 + ⌈N/size⌉

Catching it before production

Three habits that would have caught this on day one:

  1. spring.jpa.show-sql=true in dev — scroll the log; if one request prints a wall of identical selects, you’ve found it.
  2. Assert the statement count in a test. The Statistics snippet above drops straight into an integration test: seed N parents, run your service method, assert getPrepareStatementCount() is below your budget. It fails loudly the moment someone adds a lazy walk.
  3. Watch the 1+N shape, not just slowness. A request that’s “a bit slow” with 10 rows becomes a pager incident with 10,000. Query count scales with data; latency follows.

Try it yourself

Drag the sliders — the formulas are the ones verified by the runs above.

INTERACTIVE LAB
How many SQL statements does your strategy emit?
Lazy loading (N+1)
1,001SQL statements
1 + 1,000 = 1,001
findAll() then touch each collection
Lazy loading (N+1)
1,001
@EntityGraph
1
@BatchSize
11
DTO projection
1
Formulas verified against real Hibernate 6.5 runs — see the measured outputs in the article.

The takeaway

N+1 isn’t a Hibernate bug; it’s the predictable result of lazy loading meeting a loop. The fix is never “make the database faster” — it’s deciding up front what each query should return: fetch-join it, batch it, or project it. And the only way to be sure is to count: every number in this post came from a real run, and the demo above is small enough to keep in your own test suite.

Keep reading