The Wild

N+1 Problem in JPA & Hibernate: Solutions

· 6 min read · Mammals

In this article
  1. Background: Why N+1 Happens
  2. Solution 1: JOIN FETCH in JPQL
  3. Solution 2: EntityGraphs
  4. Solution 3: FetchType.EAGER (Not Recommended)
  5. Solution 4: Batch Fetching
  6. Solution 5: SUBSELECT Fetching
  7. How to Choose the Right Solution
  8. Common Pitfalls and Misconceptions
  9. Frequently Asked Questions

The N+1 query problem in JPA and Hibernate occurs when you load a collection of parent entities and Hibernate then executes one additional query for each parent to fetch its child associations. If you have N parent rows, you end up with 1 query for the parents plus N queries for the children, hence the name. The standard solution is to use a JOIN FETCH clause in JPQL, an EntityGraph, or a fetch strategy like JOIN or SUBSELECT—but each has trade-offs. This article explains the root cause, the practical fixes, and how to choose between them.

Background: Why N+1 Happens

JPA defines lazy loading as the default for @OneToMany and @ManyToMany associations. When you query a list of entities (e.g., SELECT p FROM Post p), Hibernate returns the parents without their children. The moment you access post.getComments() inside a loop, Hibernate executes a separate SELECT for each parent. That is the N+1 pattern: 1 initial query + N follow-up queries.

The problem is not unique to Hibernate—any ORM with lazy loading can exhibit it—but Hibernate’s session management and proxy creation make it particularly visible. The fix is to force the children to be fetched in the same query or to batch the child fetches.

Solution 1: JOIN FETCH in JPQL

The most direct fix is to add JOIN FETCH to your JPQL query:

SELECT p FROM Post p JOIN FETCH p.comments

This generates a single SQL query with an INNER JOIN (or LEFT JOIN if you use LEFT JOIN FETCH) that fetches both parents and children in one round trip. Hibernate will initialize the collection immediately, so no additional queries occur when you iterate.

  • Pros: Simple, explicit, and works for any query.
  • Cons: Can cause a Cartesian product if you fetch multiple collections (e.g., both comments and tags) — the result set multiplies rows, leading to memory bloat.
  • Note: If you use pagination (setFirstResult/setMaxResults), JOIN FETCH on a collection is applied in memory, which can break pagination or cause a MultipleBagFetchException.

Solution 2: EntityGraphs

EntityGraphs are a JPA standard (since JPA 2.1) that let you define fetch plans dynamically. You can use @EntityGraph on a repository method or build one programmatically:

@EntityGraph(attributePaths = {"comments"})
@Query("SELECT p FROM Post p")
List<Post> findAllWithComments();

This produces the same SQL as JOIN FETCH but keeps the query logic separate from the fetch plan. It also avoids the need to write JOIN FETCH in every query. EntityGraphs are the recommended approach in Spring Data JPA because they are declarative and can be reused.

Trade-off: EntityGraphs still generate a JOIN, so the same Cartesian product risk applies when fetching multiple collections. For a single collection, they are clean and standard.

Setting fetch = FetchType.EAGER on the association makes Hibernate always fetch the children immediately. While this eliminates N+1 for that association, it is widely considered an anti-pattern because:

  • It forces loading even when you don’t need the children, hurting performance.
  • It can cause unexpected JOINs in every query that touches the parent.
  • It cannot be overridden to be lazy later (well, you can with @LazyToOne but that’s nonstandard).

In practice, you should keep associations lazy and use explicit fetches at query time.

Solution 4: Batch Fetching

Hibernate offers @BatchSize on the collection or entity, which groups the N child queries into a smaller number of queries using WHERE id IN (?, ?, ...). For example, with @BatchSize(size = 10), if you load 100 parents, Hibernate runs 10 queries instead of 100.

Alternatively, you can set the global property hibernate.default_batch_fetch_size (e.g., 10 or 20) to apply batch fetching to all associations. This is a quick win because you don’t need to change any queries—just configuration.

  • Pros: No code changes; reduces N+1 to N/batch_size queries.
  • Cons: Still more queries than a single JOIN; not as efficient for large result sets.

Solution 5: SUBSELECT Fetching

Hibernate’s @Fetch(FetchMode.SUBSELECT) (or hibernate.default_batch_fetch_size with @Fetch(FetchMode.SUBSELECT)) runs a second query that uses a subquery to load children for all parents at once:

SELECT * FROM comments WHERE post_id IN (SELECT id FROM post WHERE ...)

This results in exactly 2 queries total, regardless of N. It is efficient for large collections but can be slower than a JOIN when the parent result set is small, because the subquery scans the whole table.

How to Choose the Right Solution

There is no one-size-fits-all; the choice depends on your query patterns and data size:

  1. Single collection, no pagination: Use JOIN FETCH or EntityGraph.
  2. Multiple collections: Use batch fetching or SUBSELECT to avoid Cartesian products.
  3. Pagination with collections: Use batch fetching or a separate query for children (e.g., a second query with IN clause).
  4. Read-only reporting: Consider a DTO projection with a constructor expression or JdbcTemplate to bypass ORM overhead.

Also, measure with SQL logging (set hibernate.show_sql=true) to see the actual query count. The goal is to minimize round trips without blowing up memory.

Common Pitfalls and Misconceptions

A frequent mistake is assuming that FetchType.EAGER solves the problem—it does, but at the cost of always loading children, which can degrade performance for queries that don’t need them. Another misconception is that JOIN FETCH always solves N+1; it does, but only for the fetched association. If you have nested collections, you may still see N+1 for deeper levels.

Also, beware of the MultipleBagFetchException. If you have two List collections and try to JOIN FETCH both, Hibernate throws this exception because it cannot handle multiple bags in a single query. The fix is to use Set instead of List, or to fetch one collection with JOIN and the other with batch fetching.

Frequently Asked Questions

Does JPA have a built-in solution for N+1?

JPA itself does not provide a direct annotation to prevent N+1; it only offers fetch strategies (LAZY/EAGER) and the EntityGraph feature (since JPA 2.1). The actual prevention requires careful query design, typically using JOIN FETCH or EntityGraph.

Is N+1 only a Hibernate problem?

No, any ORM that uses lazy loading can exhibit N+1. However, Hibernate is the most common JPA implementation, so most discussions focus on it. Other ORMs like EclipseLink have similar issues.

Can I use JOIN FETCH with pagination?

Yes, but it’s risky. If you use setFirstResult() and setMaxResults() with a JOIN FETCH on a collection, Hibernate will apply the pagination in memory after fetching all rows, which can cause a MultipleBagFetchException or memory issues. For pagination, use batch fetching or a separate count query.

What is the difference between JOIN FETCH and EntityGraph?

Both generate the same SQL, but EntityGraph is a JPA standard and can be reused across multiple queries without modifying the JPQL. JOIN FETCH is a JPQL clause that is part of the query itself. EntityGraph is generally preferred in Spring Data JPA because it’s declarative.

Is batch fetching always faster than JOIN FETCH?

Not necessarily. For a small number of parents (e.g., 5), a single JOIN is faster than 5 batch queries. For a large number (e.g., 1000), batch fetching with a size of 20 reduces queries to 50, which may be slower than a single JOIN but avoids the Cartesian product risk. The best choice depends on your data size and query pattern.