Sub topic 3
Lazy versus eager fetching
This chapter assumes you can read JPA entity mappings, know what a Spring Data repository is, and have seen the Author and Book model from the earlier chapters. It explains what "lazy" and "eager" mean in JPA, what the defaults are, and why the choice decides how many SQL statements your application runs.
What a fetch type controls
A fetch type tells the JPA provider (Hibernate, in a Spring Boot application) when to load an association. An association is a field that points to another entity or to a collection of entities.
FetchType.LAZYmeans the provider loads the associated data later, the first time your code touches it.FetchType.EAGERmeans the provider loads the associated data at the same time as the owning entity.
You set the fetch type on the mapping annotation:
@ManyToOne(fetch = FetchType.LAZY)
private Author author;The fetch type is a global rule for that field. It applies to every query that loads the entity, including queries you wrote for a different purpose. That is the main reason it is easy to get wrong.
The defaults
JPA defines a default for each association annotation. The defaults are not symmetrical.
| Annotation | Default fetch type |
|---|---|
| `@OneToMany` | `LAZY` |
| `@ManyToMany` | `LAZY` |
| `@ManyToOne` | `EAGER` |
| `@OneToOne` | `EAGER` |
| `@Basic` (plain columns) | `EAGER` |
The rule of thumb: associations that point to many things are lazy, and associations that point to one thing are eager. In the example model, Author.books is lazy without any extra configuration. Book.author would be eager if we did not set it. The model in this tutorial sets it to lazy on purpose:
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
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
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
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; }
}How lazy loading works inside Hibernate
Lazy loading is not magic. Hibernate puts a stand-in object where the real data would be. What the stand-in looks like depends on the kind of association.
Lazy collections
For a @OneToMany field, Hibernate replaces your ArrayList with its own collection implementation, such as PersistentBag. This object looks like a List, but it holds no elements yet. The first call that needs the elements, such as size(), iterator(), or get(0), makes it run a SELECT for the child rows. This step is called initializing the collection.
Calling getBooks() alone does not trigger a query. It only returns the uninitialized wrapper. The query runs when you use the contents.
Lazy single-valued associations
For a @ManyToOne or @OneToOne field marked lazy, Hibernate creates a proxy. A proxy is a generated subclass of your entity class whose fields are empty. When you call a method that needs data, such as getTitle() on a proxied Book, the proxy loads the real row and forwards the call.
The identifier is an exception. Calling getId() on a proxy normally does not trigger a load, because the proxy already knows the id from the foreign key column.
Because the proxy is a subclass, your entity classes should not be final, and they need a constructor that Hibernate can call (a no-argument constructor with at least protected visibility). Hibernate also relies on you to use getters rather than reading fields directly from outside the class, since a direct field read on a proxy returns null.
Why this needs an open session
A lazy load is a database call, and a database call needs a connection that belongs to a persistence context. Initialization works only while the entity is still managed by an open session. If you touch a lazy association after the session has closed, Hibernate throws LazyInitializationException. A later chapter covers Open Session in View, which is the Spring Boot setting that keeps the session open longer than most people expect.
A lazy load in practice
Consider this service, which comes from the tutorial's running example:
@Service
public class AuthorService {
private final AuthorRepository authorRepository;
public AuthorService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAll().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}
}findAll() runs one SELECT on the author table. It does not touch the book table, because books is lazy. Each a.getBooks().size() then initializes one collection, which sends one more query per author. The method is correct and returns the right answer. It is also the shape of the N+1 problem, which the next chapter takes apart in detail. For now, notice that nothing in the method's code shows the extra queries. They come from the mapping.
The sequence below shows what happens for a single author.
What eager fetching does
Eager fetching loads the association together with the owner. Hibernate chooses how: sometimes by joining the tables in the same statement, and sometimes by issuing a second statement right away. The choice depends on how you load the entity.
- When you load by primary key (
entityManager.findorrepository.findById), Hibernate usually builds one statement with an outer join to the eager association. - When you load with a query (a JPQL query, a derived query method, or
findAll()), Hibernate runs your query first and then loads each eager association with extra statements. The query you wrote does not know about the mapping's eager setting, so it cannot add the join itself.
The second case is the dangerous one. If Book.author were eager, then bookRepository.findAll() would run one query for books, and then one more query for each distinct author that appears. You get N+1 behavior without ever touching a getter, and without a way to turn it off for a query that does not need the author.
The eager chain
Eager associations also chain. If Book.author is eager and Author.publisher is eager, loading one book pulls in its author, then the author's publisher, and so on through the graph. One innocent findById can load a large part of the database. A mapping change made for one screen then slows down every other use of that entity.
Why lazy is the better default
Eager fetching is a global promise that you cannot cancel per query. Lazy fetching leaves the decision to each query, which is where the knowledge about what is needed actually lives. The common advice is:
- Map every association as
LAZY, including@ManyToOneand@OneToOne. - For each use case, fetch what it needs explicitly with
JOIN FETCH, an entity graph, or a DTO projection. - Treat any
EAGERmapping as something that needs a written reason.
You can move from lazy to eager for one query, but you cannot move from eager to lazy for one query. That asymmetry is the reason to start lazy.
Lazy is a hint, not a guarantee
The JPA specification says LAZY is a hint that the provider may ignore, while EAGER is a requirement. In practice Hibernate honors lazy for collections and for @ManyToOne. Two cases deserve attention.
The inverse side of `@OneToOne`
On the side of a one-to-one relationship that does not own the foreign key (the mappedBy side), Hibernate cannot tell whether the other row exists without querying for it. It has to know whether to put null or a proxy in the field. So it loads the other row right away, even when you asked for LAZY. Ways around this include making the association optional on the owning side with a shared primary key (@MapsId), or modeling the relationship as @ManyToOne from the owning side only.
Basic attributes
Large columns such as a @Lob are also loaded with the row by default. Lazy loading of individual columns needs bytecode enhancement, which is a build-time step and outside the scope of this chapter. If you have a large column that most queries do not need, a DTO projection or a separate entity for the large data is usually simpler.
Common mistakes
- Assuming
@OneToManyis the only source of N+1. A lazy@ManyToOnealso causes it, for example when a loop callsbook.getAuthor().getName()on many books. - Switching a collection to
EAGERto stop the exception. This hidesLazyInitializationExceptionbut makes every load of the entity pay for the collection, and it does not fix N+1 for queries. - Calling
Hibernate.initializeorsize()in a loop. It works, and it creates exactly the N+1 pattern you are trying to avoid. - Expecting
getBooks()to run a query. It does not. The query runs at first use of the contents. - Serializing entities directly to JSON. The JSON library walks every getter, which initializes every lazy association it can reach, or fails when the session is closed.
Checking what you have
You can see the effect of your mappings by turning on SQL logging and Hibernate statistics. The settings below also turn off Open Session in View, so a lazy load outside a transaction fails visibly instead of silently running a query.
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.SQL=DEBUGRun authorSummaries() against a table with five authors. The log shows one statement for the authors, followed by five statements of the form select ... from book where author_id = ?. With the lazy mapping you will see six statements. Changing nothing but the query, as the following chapters do, brings that down to one.
Exercise
A teammate changes Book.author from FetchType.LAZY to FetchType.EAGER so that bookRepository.findAll() no longer causes a LazyInitializationException in a controller. Describe what happens to the SQL for findAll() on 100 books written by 20 authors, and name a better fix.
Show answer
findAll() runs a JPQL-style query that ignores the eager setting, so Hibernate first runs one select for the 100 books. It then loads the eager author association with extra statements, one for each distinct author not already in the persistence context, which is about 20 more queries, so roughly 21 in total. Every other query that loads Book now pays this cost too, including ones that never need the author. A better fix is to keep the association lazy and load the authors in the query that needs them, with join fetch b.author, an @EntityGraph, or a DTO projection that selects only the needed columns.
Exercise
Which of these default to LAZY in JPA: @OneToMany, @ManyToOne, @ManyToMany, @OneToOne? Then explain why calling author.getBooks() does not by itself run a query.
Show answer
@OneToMany and @ManyToMany default to LAZY. @ManyToOne and @OneToOne default to EAGER. getBooks() returns Hibernate's uninitialized collection wrapper (for example a PersistentBag). The SELECT runs only when the code first needs the elements, such as through size(), iterator(), or get(int), and only while the session is still open.