Symptom: one endpoint or service method is slow, and the SQL it runs grows with the number of rows returned. You see one query for the parent rows, then one more query per row for its associated state.
That is the N+1 pattern. The Hibernate User Guide describes it as one query that loads the owners, followed by many separate queries for their associated state.
This guide was written for Hibernate 7.4.15.Final, which requires JPA 3.2 and Java 17 or 21. The Spring Data JPA and Spring Boot versions are not pinned here, so check the reference pages for the versions you run.
Spot the problem before you change anything
Measure first. A plan does not promise an exact number of SQL statements, because the result depends on context state, caches, the dialect and other mapping requirements. Guessing from the mapping alone is unreliable.
Hibernate exposes counters through its Statistics interface. Collection of statistics is enabled when the configuration property hibernate.generate_statistics is true. You can also switch it on at runtime with setStatisticsEnabled(boolean).
Statistics reports the global number of executed queries, entity fetches and collection fetches, and clear() resets all counters. The exact getter names are in the Javadoc for org.hibernate.stat.Statistics. Check them there before you write code against them.
How you pass hibernate.generate_statistics to Hibernate from Spring Boot is not shown on the Spring Boot SQL Databases page. Look there and in the Spring Boot reference for the property prefix that forwards settings to the JPA provider. The same applies to enabling SQL logging: this guide does not name a logging flag, so use the one your Spring Boot version documents.
A reliable baseline is this: call clear(), run one operation, then read the executed-query count. If the count grows with the number of parent rows, you have N+1. If it stays flat, the slowness is elsewhere.
The example model used below
The examples use an Author that owns a collection of Book entities. Collections default to lazy loading, so each Author loads its books on first access.
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}
@Entity
class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
private Author author;
public Long getId() { return id; }
public String getTitle() { return title; }
public Author getAuthor() { return author; }
}
Cause 1 (most likely): a lazy association is read inside a loop
A derived query such as findAll() loads only the owners. When your code then calls author.getBooks() for each row, Hibernate runs an individual select for each unloaded collection. This is the classic N+1.
The Hibernate guide states it plainly: an individual select is susceptible to N+1, but it does not necessarily cause it. Associated entities might already be loaded or available from a cache.
Fix: ask for the state the operation needs in the query itself. A query fetch join is one documented way. Entity graphs and fetch profiles are the others the Hibernate guide lists for customising an operation's plan.
Declare the query with @Query, which Spring Data JPA documents for queries the method name cannot express well.
The Spring Data JPA query methods page also covers @EntityGraph for fetch and load graphs. Read it for the attribute syntax, because this guide does not reproduce it.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select distinct a from Author a join fetch a.books")
List<Author> findAllWithBooks();
}
Cause 2: to-one associations that load eagerly
@ManyToOne and @OneToOne associations can be eager. The Hibernate guide says the persistence unit's default to-one fetch type is initially EAGER, and that you can choose LAZY as the unit default instead of repeating it on every mapping. An explicit fetch=EAGER or fetch=LAZY on an attribute overrides that default.
That passage describes the newer Jakarta Persistence FetchType.DEFAULT behaviour. Your project targets JPA 3.2, so check the Hibernate guide for your version to see how the default is resolved. The reliable move is to set fetch = FetchType.LAZY explicitly, as Book.author does above.
The guide's advice is: prefer lazy association defaults and request the state needed by each operation. Then fix each hot path with a fetch join or a graph, as in cause 1.
Note that lazy fetching is a hint in Jakarta Persistence, not a guarantee that no state is retrieved early.
Cause 3: the mapping uses FetchMode.SELECT and many owners are loaded
org.hibernate.annotations.Fetch selects a mapping-level method through FetchMode. With SELECT, Hibernate uses a secondary select, so accessing each unloaded collection may execute a separate select. The Hibernate guide uses this exact setup to illustrate N+1.
If you cannot rewrite every caller, change how the collections are loaded in groups. The guide lists two methods that reduce secondary queries without joining all associated rows into the owner query:
- Batch: retrieves several entities or owner collections together using their identifiers.
- Subselect: retrieves associated state using a subquery based on the query that loaded the owners.
For subselect, annotate the collection with FetchMode.SUBSELECT. Hibernate supports it for collections and to-one associations.
The batch setting's name is not covered here. Look it up in the Hibernate User Guide fetching chapter.
Do not confuse org.hibernate.annotations.Fetch with jakarta.persistence.Fetch, which customises an attribute in a named entity graph.
import jakarta.persistence.OneToMany;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import java.util.ArrayList;
import java.util.List;
// Inside the Author entity, replace the books mapping with:
@OneToMany(mappedBy = "author")
@Fetch(FetchMode.SUBSELECT)
private List<Book> books = new ArrayList<>();
Cause 4: you expected FetchMode.JOIN to fix a query
FetchMode.JOIN joins the associated state when you load the owner directly, by identifier or natural id. It implies eager loading, even if the association declares fetch=LAZY.
The Hibernate guide is explicit that an entity query does not automatically reproduce these mapping joins. A repository query such as findAll() can therefore still produce N+1 despite the mapping.
Fix: use a query fetch join or an appropriate graph for that query, as in cause 1. Treat FetchMode.JOIN as a tool for direct loads only.
Because JOIN forces eager loading, it can also load state that operations never use. Loading unnecessary rows increases transfer, processing and memory cost.
Confirm the fix worked
Repeat the baseline from the first section on the same data.
- Call
clear()on theStatisticsobject. - Run the operation, for example
findAllWithBooks()followed by reading everygetBooks(). - Read the global executed-query count and the collection fetch count.
With a working fetch join the query count is constant, regardless of how many authors exist. Add more rows to your test data and run it again. If the count still grows with row count, a different association is being loaded lazily. Repeat the diagnosis for that association.
Put the assertion in a test so a future mapping change cannot silently bring the problem back.
When it is not N+1
Extra queries do not always mean N+1. Entities may already be in the persistence context or in a cache, which removes the secondary selects. A count that is high but flat across data sizes points to something other than this pattern.
A collection fetch join also has a cost: it joins associated rows into the owner query. Compare it with batch or subselect fetching when collections are large. The HQL chapter of the Hibernate guide covers how fetch-joined collection results are returned.
Troubleshooting
| Problem | Likely cause | Fix |
|---|---|---|
| The query count is still high after adding a fetch join. | A different lazy association, often on the child entity or another to-one mapping, is read in the same loop. | Clear the statistics, rerun, and compare the counts per entity and per collection role. Fetch join, graph or batch that association too. |
| Statistics counters always read zero. | Statistics collection is not enabled, so hibernate.generate_statistics is not true. | Set hibernate.generate_statistics to true through the property-forwarding mechanism of your Spring Boot version, or call setStatisticsEnabled(boolean) at runtime. |
| Setting a fetch join returns duplicate owners. | A collection join produces one row per child, so the same owner can appear more than once. | Use select distinct in the JPQL, as in findAllWithBooks. For details on result handling, read the HQL chapter of the Hibernate User Guide. |
| Mapping is FetchMode.JOIN but the repository query still runs extra selects. | Entity queries do not reproduce mapping joins. | Add a query fetch join or an entity graph to that repository method. |
| A LAZY mapping still loads state early. | Jakarta Persistence defines lazy fetching as a hint, not a guarantee. | Verify with statistics rather than assuming, and request the needed state explicitly per operation. |
Frequently asked questions
Does a lazy association always cause N+1?
No. An individual select is susceptible to N+1, but associated entities might already be loaded or available from a cache, so extra queries are not guaranteed.
How do I count queries in Hibernate?
Enable hibernate.generate_statistics or call setStatisticsEnabled(boolean), then read the Statistics interface. It reports the global number of executed queries. Check the Javadoc for exact method names.
Is FetchMode.JOIN a fix for N+1 in repository queries?
No. It applies when you load the owner directly, and entity queries do not automatically reproduce those mapping joins. Use a query fetch join or a graph.
What is the difference between batch and subselect fetching?
Batch retrieves several entities or owner collections together using their identifiers. Subselect retrieves associated state with a subquery based on the query that loaded the owners.
Which Hibernate version does this apply to?
It was written for Hibernate 7.4.15.Final with JPA 3.2. Check the user guide for your version if you run another release.
References
From Grokem: https://www.grokem.com/programming/web-development/web-performance/fix-spring-data-jpa-n1-queries-in-spring-boot-spot-the-cause-confirm-the-cure








