Sub topic 3
Lazy versus eager fetching
This chapter assumes you know basic JPA mapping (@Entity, @Id, @OneToMany, @ManyToOne), Spring Data JPA repositories, and how a Spring @Transactional method works. It uses the Author and Book model from the earlier chapters.
What a fetch type decides
A fetch type tells JPA when to load a related entity or collection. There are two choices:
FetchType.LAZYloads the association the first time your code touches it.FetchType.EAGERloads the association at the same time as its owner, every time the owner is loaded.
The defaults depend on the kind of relationship.
| Annotation | Default fetch type |
|---|---|
| `@OneToMany` | `LAZY` |
| `@ManyToMany` | `LAZY` |
| `@ManyToOne` | `EAGER` |
| `@OneToOne` | `EAGER` |
The @ManyToOne default is the one that surprises people. If you do not set it, loading a Book also loads its Author.
The example mapping
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; }
}Author.books is lazy because that is the default for @OneToMany. Book.author is lazy because the mapping says so explicitly, which overrides the eager default.
What lazy loading looks like at runtime
Hibernate does not leave the lazy field empty. It puts a stand-in there:
- For a collection, it assigns a special collection object (a
PersistentBagfor aList). The object holds no rows until you read it. - For a single-valued association, it assigns a proxy. A proxy is a generated subclass of your entity that knows only the id. Calling any other getter makes it run a
select.
The query runs on first access, through the persistence context. If the persistence context is closed by then, Hibernate throws a LazyInitializationException. In a service method annotated with @Transactional, the context stays open and the load works.
Why eager is not the fix
Eager loading looks like a way to avoid lazy-loading surprises, but it has three costs:
- It applies to every query. A screen that needs only author names still pays for the books.
- You cannot switch it off per query. A
LAZYmapping can be made eager for one query withJOIN FETCH. AnEAGERmapping cannot be made lazy for one query. - Associations that are eager are loaded for each entity returned by a JPQL query or derived repository method, often with one extra select per row. This is the N+1 problem again, hidden in the mapping.
Common errors
- Assuming
LAZYis a guarantee. It is a hint in the JPA specification. Hibernate honors it for collections and for@ManyToOne. A@OneToOneon the side that does not own the foreign key often loads eagerly anyway, because Hibernate must query to know whether the value isnull. - Touching a lazy field outside a transaction. This throws
LazyInitializationException. Do not fix it by making the field eager. Load the data you need inside the transaction. - Treating lazy as free. Lazy loading defers cost, and it can multiply it. Reading a lazy collection for each row of a list is the start of the N+1 problem, which the next chapter covers.
Exercise
You load a Book with findById. The Book.author mapping is @ManyToOne with no fetch attribute. What happens, and what change makes the author load only when needed?
Show answer
With no fetch attribute, @ManyToOne is EAGER, so Hibernate loads the Author together with the Book. Setting @ManyToOne(fetch = FetchType.LAZY) makes Hibernate put a proxy in author, and the Author row is selected only when you call a getter other than the id getter on it.