Sub topic 1
JPA Performance and the N+1 Problem in Spring Boot
Prerequisites.
Assume you know basic Java, Spring Boot, Spring Data JPA repositories, SQL joins, and JPA annotations such as @Entity, @Id, @OneToMany, and @ManyToOne.
The example model: authors and books
An author can write many books. Each book belongs to one author. This is a bidirectional one-to-many relationship: both entities can navigate to the other.
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
@OneToMany(mappedBy = "author")
List<Book> books = new ArrayList<>();
}
@Entity
class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String title;
@ManyToOne(fetch = FetchType.LAZY)
Author author;
}mappedBy = "author" says that Book.author owns the database relationship. The books field is the inverse side.
What the persistence context does
The persistence context is the set of entities that the current transaction manages. Hibernate stores loaded entities there and tracks their changes. It also keeps references that can load related data later.
When Hibernate loads an Author, it may place a proxy object or a lazy collection in the entity. The related books are not necessarily read immediately. Hibernate can query them when the application accesses author.books.
Lazy versus eager fetching
Lazy fetching loads a relationship only when code uses it. Eager fetching loads it as part of the initial operation or soon afterward. Lazy fetching is usually safer as a default because it avoids reading unused data, but it requires a deliberate query plan.
How the N+1 select problem happens
Suppose a repository loads 10 authors. The first query reads all authors. Then code calls getBooks() for each author. Hibernate may issue one additional query per author: one query plus 10 more, or 11 statements total.
Exercise
What does N+1 mean when loading authors and books?
Show answer
Hibernate runs one query for the authors and one additional query for each author whose books are accessed.