Sub topic 13
Lazy loading, N+1 selects and fetch strategies
This chapter assumes you can map entities with @ManyToOne and @OneToMany, write Spring Data repositories, and use @Transactional. The examples use the Author, Book, BookRepository and CatalogService classes from earlier chapters.
Eager and lazy loading
A fetch type tells JPA when to load an association. There are two values.
FetchType.EAGERloads the association together with the owning entity.FetchType.LAZYloads the association the first time your code reads it.
The JPA defaults differ by association type.
| Association | Default fetch type |
|---|---|
| `@ManyToOne` | EAGER |
| `@OneToOne` | EAGER |
| `@OneToMany` | LAZY |
| `@ManyToMany` | LAZY |
The safe habit is to declare every association LAZY, as Book.author already does:
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "author_id")
private Author author;Eager loading looks convenient, but it is a fixed decision. You cannot turn it off for a query that does not need the association. Lazy loading lets each query decide what to load.
How lazy loading works
For a lazy @ManyToOne, Hibernate does not put the real Author into book.author. It puts a proxy, which is a generated subclass of Author that holds only the identifier. The first call to a method that needs data, such as getName(), makes the proxy run a select.
For a lazy collection, Hibernate puts in its own collection implementation (PersistentBag). Reading its contents, for example by iterating or calling size(), triggers the select.
Both mechanisms need an open persistence context. The proxy asks the EntityManager that loaded it to run the query. If that context is closed, the proxy cannot load anything.
The LazyInitializationException
This exception means you touched an uninitialized proxy or collection after its persistence context was closed. The most common cause is returning entities from a transactional service and reading a lazy association in a controller or serializer.
@Service
public class CatalogReader {
private final BookRepository books;
public CatalogReader(BookRepository books) {
this.books = books;
}
@Transactional(readOnly = true)
public Book load(Long id) {
return books.findById(id).orElseThrow();
}
}Book book = reader.load(1L);
// The transaction has ended, so the persistence context is closed.
String name = book.getAuthor().getName(); // LazyInitializationExceptionHere book.getAuthor() returns an uninitialized proxy. Calling getName() on it fails.
There are several fixes. The first two are preferred.
- Load what you need inside the transaction, using a join fetch or entity graph (shown below).
- Return a DTO or projection from the service, so no lazy state leaves the transaction.
- Read the association inside the transactional method, which initializes it.
Avoid two shortcuts that remove the symptom and keep the problem:
- Switching the association to
EAGERmakes every query load it. - Spring Boot's
spring.jpa.open-in-viewsetting istrueby default. It keeps the persistence context open during the web request, so lazy loads in the view layer work. The cost is that database queries can run anywhere in the request, and a database connection can be held for the whole request. Many teams setspring.jpa.open-in-view=falseso that lazy loading errors show up in development.
The N+1 select problem
N+1 happens when you run one query to load N entities, then one extra query per entity to load a lazy association. Consider this service method:
@Transactional(readOnly = true)
public List<String> describeBooks(int year) {
return books.findAll().stream()
.map(b -> b.getTitle() + " by " + b.getAuthor().getName())
.toList();
}With 100 books by 40 authors, Hibernate runs one select on books. Then, each time it meets an author it has not loaded yet, it runs select ... from authors where id = ?. The first query returns N rows, and the loop adds up to N more queries. Authors already in the persistence context are not loaded again, so the extra count is the number of distinct authors, not the number of books.
Each extra query costs a network round trip. The problem is invisible with small test data and shows up as slow pages in production.
Detecting N+1
Turn on SQL logging in development:
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUGRun the code path and count the statements. Repeated statements that differ only in the id are the sign. For automatic detection, Hibernate statistics (spring.jpa.properties.hibernate.generate_statistics=true) report the number of prepared statements per session. A test can assert that count, so a regression fails the build.
Fix 1: join fetch in JPQL
join fetch tells Hibernate to load the association in the same select. The repository already has this:
@Query("select b from Book b join fetch b.author where b.publishedYear = :year")
List<Book> findByYearWithAuthor(@Param("year") int year);The generated SQL is one inner join, and each returned Book has a fully loaded author. Use left join fetch when the association can be null or empty and you still want the owner row.
Fix 2: entity graphs
An entity graph names the associations to load for a query. In Spring Data you attach it with @EntityGraph on a repository method, which suits derived queries because you do not have to write JPQL:
@EntityGraph(attributePaths = "author")
List<Book> findByAuthorName(String name);Entity graphs use a left outer join by default. They are a good fit when the query is already expressed by the method name and you only want to add loading behavior.
Fetching collections: limits and pitfalls
Join fetching a @ManyToOne is safe, because each book has one author. Join fetching a collection has costs.
- Row duplication. Fetching
Author.bookswith a join returns one row per book. Older Hibernate versions then return the sameAuthorseveral times, so you wroteselect distinct. Hibernate 6 deduplicates entity results automatically, but check your version. - Paging. Combining a collection fetch with
Pageablemakes Hibernate warnHHH000104: firstResult/maxResults specified with collection fetch; applying in memory. It loads every row and pages in the JVM. Do not page over a collection join fetch. - MultipleBagFetchException. Fetching two
Listcollections in one query fails, because Hibernate cannot tell the duplicated rows apart. Fetch one collection per query, or useSet.
For paged queries, a common approach is two steps. First page over the ids or the root entities. Then load the collections for that page with a second query using where a.id in :ids.
Fix 3: batch fetching
When you cannot restructure the query, batch fetching reduces the query count without changing the code. Set a batch size:
spring.jpa.properties.hibernate.default_batch_fetch_size=20Now when Hibernate must load one uninitialized author or collection, it loads up to 20 pending ones in a single where id in (...) query. A hundred lazy loads become five. This is a good default for large applications. It does not beat a join fetch for a known access path, but it covers paths you did not tune.
Choosing a strategy
| Situation | Approach |
|---|---|
| You know exactly which association the use case needs | `join fetch` or `@EntityGraph` on that query |
| The query is a derived method | `@EntityGraph` |
| Paged result, association is `@ManyToOne` | Join fetch or entity graph, safe with paging |
| Paged result, association is a collection | Two queries, or batch fetching |
| You only need a few columns | A projection, which avoids loading entities at all |
| Many unpredictable lazy accesses | `default_batch_fetch_size` as a safety net |
Keep associations lazy by default, then add fetching per query. This puts the loading decision where the use case is known.
Verifying with a test
You can lock in the fix with a test that counts statements. With Hibernate statistics enabled in the test properties:
import jakarta.persistence.EntityManager;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")
class FetchTest {
@Autowired
private BookRepository books;
@Autowired
private TestEntityManager tem;
@Test
void joinFetchLoadsAuthorsInOneStatement() {
for (int i = 0; i < 3; i++) {
Author a = new Author("Author " + i);
a.addBook(new Book("Book " + i, 2000));
tem.persist(a);
}
tem.flush();
tem.clear();
SessionFactory sf = tem.getEntityManager()
.getEntityManagerFactory().unwrap(SessionFactory.class);
sf.getStatistics().clear();
var result = books.findByYearWithAuthor(2000);
result.forEach(b -> b.getAuthor().getName());
assertThat(sf.getStatistics().getPrepareStatementCount()).isEqualTo(1);
}
}The call to tem.clear() matters. Without it, the authors are still in the persistence context from the inserts, and the test would pass even with a lazy query.
Exercise
A controller calls bookService.findAll(), which returns List<Book> from a @Transactional method, and then a JSON serializer reads book.getAuthor().getName(). With spring.jpa.open-in-view=false this throws LazyInitializationException. Name two fixes that keep Book.author lazy.
Show answer
Load the author inside the transaction, for example with a join fetch query or @EntityGraph(attributePaths = "author") on the repository method. Or return a DTO or projection (title and author name) built inside the transaction, so no proxy leaves it. Setting the association to EAGER or turning open-in-view back on would hide the error but not fix the design.
Exercise
You add join fetch b.tags (a List collection) to a query that takes a Pageable, and the log shows HHH000104. What is happening, and what is a better approach?
Show answer
Hibernate cannot apply SQL limit correctly over a joined collection, because rows are duplicated per child. It loads all rows and pages in memory, which is slow and memory heavy. Page over the root entities (or their ids) first, then load the collection for that page with a second query using in :ids, or rely on default_batch_fetch_size.