Sub topic 13
Lazy loading, N+1 selects and fetch strategies
This chapter assumes you can map entities with @ManyToOne and @OneToMany, write repository methods, and read basic SQL. It uses the Author and Book entities from the earlier chapters.
How lazy loading works
A fetch type tells JPA when to load an association. FetchType.LAZY loads it on first access. FetchType.EAGER loads it together with the owner.
Defaults differ by association type:
| Association | Default fetch type |
|---|---|
| `@ManyToOne`, `@OneToOne` | EAGER |
| `@OneToMany`, `@ManyToMany` | LAZY |
Set @ManyToOne to LAZY explicitly, as Book.author does. Eager loading cannot be turned off per query, so it often loads data you never use.
For a lazy association, Hibernate puts a proxy (a placeholder object) or an uninitialized collection in the field. The first access on it runs a select. That select needs an open session, so it normally works only inside a transaction.
The N+1 select problem
Suppose you load 50 books and print each author's name.
List<Book> found = books.findByTitleContainingIgnoreCase("the");
for (Book b : found) {
System.out.println(b.getAuthor().getName());
}Hibernate runs one select for the books. Each distinct author then triggers one more select the first time its name is read. With 50 authors, that is 51 statements: 1 for the list plus N for the associations.
You may not notice this with a small test database. It shows up as slow requests with larger data. To find it, enable SQL logging with spring.jpa.show-sql=true, or count statements in tests.
Fixing it
Load the association in the same query. Two options appear in BookRepository.
@Query("select b from Book b join fetch b.author where b.publishedYear = :year")
List<Book> findByYearWithAuthor(@Param("year") int year);
@EntityGraph(attributePaths = "author")
List<Book> findByAuthorName(String name);join fetchin JPQL changes one query to load the association with a SQL join.@EntityGraphadds the same fetch to a derived query method, so you do not have to write JPQL.
Each produces one select. Use them where the caller needs the association, instead of making the mapping eager for everyone.
A third option is batching. Setting spring.jpa.properties.hibernate.default_batch_fetch_size=50 makes Hibernate load up to 50 lazy associations per select. It reduces N+1 to about N/50 + 1 without changing queries.
LazyInitializationException
If you touch a lazy association after the transaction ends, Hibernate has no session to run the select. It throws LazyInitializationException.
Book book = books.findById(1L).orElseThrow(); // transaction ends here
book.getAuthor().getName(); // fails if author is an uninitialized proxyFixes, in order of preference:
- Fetch what you need in the query, with
join fetchor@EntityGraph. - Map the data to a DTO inside the transactional service method, so callers never touch entities.
- Widen the transaction with
@Transactionalon the service method that uses the data.
Exercise
A page lists 20 orders and shows each order's customer name through a lazy @ManyToOne. The log shows 21 selects. Why, and what is one fix?
Show answer
Hibernate runs one select for the orders and one per distinct customer when its name is read first (N+1). Fix it by loading the customer in the same query, with join fetch in JPQL or @EntityGraph(attributePaths = "customer") on the repository method.