Sub topic 1
The example model: authors and books
Overview
Every later chapter in this tutorial uses one small model: an Author who has many Book entries. It has one collection and one single-valued association, so it can show every fetching problem we need. This chapter defines the model, explains each mapping decision, and sets up a seeded database. Later chapters measure and fix queries against it.
Prerequisites
This chapter assumes you have:
- A working Spring Boot 3 application (Spring Boot 3 uses the
jakarta.persistencepackage, notjavax.persistence). - Spring Data JPA on the classpath, plus an in-memory database such as H2 for experiments.
- Basic familiarity with
@Entity,@Id,@OneToManyand@ManyToOne. - Basic SQL, including joins and
GROUP BY.
You do not need to know what the persistence context is yet. The next chapter covers it.
The relational shape
An author writes many books, and each book here has exactly one author. In the database, the foreign key lives on the book table. The author table knows nothing about its books.
This one-to-many relationship appears in most real schemas: orders and order lines, users and roles, posts and comments. A fix that works here usually transfers to those schemas.
The entities
Here are the two entities. Each public class goes in its own file, in the same package. The package name com.example.library is only a placeholder.
package com.example.library;
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<>();
protected Author() {
}
public Author(String name) {
this.name = name;
}
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
public void addBook(Book book) {
books.add(book);
book.setAuthor(this);
}
}package com.example.library;
import jakarta.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
private Author author;
protected Book() {
}
public Book(String title) {
this.title = title;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public Author getAuthor() { return author; }
void setAuthor(Author author) {
this.author = author;
}
}Why the mapping looks this way
Owning side and inverse side. In a bidirectional association, exactly one side owns the foreign key. Here Book.author is the owning side. It maps to the author_id column, which Hibernate names by default from the field name and the target's id column. Author.books is the inverse side. The attribute mappedBy = "author" says "the foreign key is managed by the author field on Book".
If you leave out mappedBy, Hibernate treats books as a second, independent association and creates a join table called author_books. This is a common mapping mistake, and it changes the SQL in every later chapter.
Changes on the inverse side are ignored. Hibernate writes the foreign key only from the owning side. If you call author.getBooks().add(book) but never set book.author, the author_id column stays null after the flush. The addBook helper updates both sides together, so the in-memory graph and the database agree.
Package-private setter. Book.setAuthor has no public modifier, so only code in the same package, namely Author.addBook, can call it. This keeps callers from setting one side of the relationship and forgetting the other.
No-argument constructors. JPA requires a no-argument constructor on every entity, and it may be protected. Hibernate also uses it to create proxies, which are runtime subclasses that stand in for an entity that has not been loaded. For that reason, do not mark entity classes final.
The collection is initialized. books = new ArrayList<>() means new, unsaved authors never have a null collection. When Hibernate loads an author from the database, it replaces this list with its own collection wrapper, which can load its contents on demand.
No cascade. The model has no cascade setting. Saving an author does not save its books, and you must save both. That is more code, but it keeps behavior visible. Cascade rules can change the number of statements and are unrelated to the problem we study.
Fetch defaults are different for each side
The two associations behave differently even though both look like plain annotations.
| Association | Annotation | JPA default fetch | In this model |
|---|---|---|---|
| `Author.books` | `@OneToMany` | `LAZY` | Default, so not loaded until accessed |
| `Book.author` | `@ManyToOne` | `EAGER` | Overridden to `LAZY` |
The JPA specification makes @ManyToOne and @OneToOne eager by default, and @OneToMany and @ManyToMany lazy by default. Setting fetch = FetchType.LAZY on @ManyToOne is a deliberate choice. If we left it eager, loading a list of books would also load each book's author, and you would get extra queries even in code that never touches the author.
The "Lazy versus eager fetching" chapter covers what lazy means in practice and why eager is rarely the better choice.
The query side
Spring Data repositories give us the access layer. We need one for each entity:
package com.example.library;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AuthorRepository extends JpaRepository<Author, Long> {
}package com.example.library;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}Later chapters add query methods to AuthorRepository. BookRepository stays empty unless a chapter says otherwise.
Seed data and configuration
To see N+1 behavior, you need several authors, each with several books. This runner inserts five authors with three books each when the application starts:
package com.example.library;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class DataSeeder implements ApplicationRunner {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public DataSeeder(AuthorRepository authorRepository, BookRepository bookRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
}
@Override
public void run(ApplicationArguments args) {
for (int a = 1; a <= 5; a++) {
Author author = authorRepository.save(new Author("Author " + a));
for (int b = 1; b <= 3; b++) {
Book book = new Book("Book " + a + "." + b);
author.addBook(book);
bookRepository.save(book);
}
}
}
}The runner is not transactional, so each save call commits on its own. That is fine for seeding. It is also why the seeding statements are easy to tell apart from the queries we examine later.
Add these properties so the schema is created for you and the SQL becomes visible:
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false
logging.level.org.hibernate.SQL=DEBUGThe logging.level.org.hibernate.SQL setting prints each statement through your logging framework. It is preferred over show-sql, which prints directly to standard output. The Hibernate-generated table definitions will look roughly like this:
create table author (id bigint generated by default as identity, name varchar(255), primary key (id));
create table book (id bigint generated by default as identity, title varchar(255), author_id bigint, primary key (id));
alter table book add constraint fk_book_author foreign key (author_id) references author;The constraint name Hibernate generates is a hashed string, so treat fk_book_author as a stand-in. The column layout matches the diagram.
Edge cases to keep in mind
- Identity generation.
GenerationType.IDENTITYmakes the database assign ids, so Hibernate must run eachinsertimmediately to learn the id. This disables JDBC insert batching. The "JDBC batching for inserts and updates" chapter returns to this. It is fine for this model, but not a free choice in write-heavy code. Listas a bag. Without@OrderColumn, aListmapping is a bag: an unordered collection that allows duplicates. Bags have particular consequences when you fetch more than one collection at once, which we cover later.toString,equalsandhashCode. Do not includebooksintoString()orhashCode(). Doing so would silently trigger lazy loading, and it breaks in the same way our later examples do.- Nullable foreign key. The model lets a book exist without an author, because
author_idis nullable by default. Add@JoinColumn(nullable = false)if your domain forbids that.
What the model sets up
Reading findAll() on authors gives you five Author objects. Each one's books collection exists but holds nothing yet. The data is loaded only when the code touches it. The next two chapters explain the machinery behind that behavior: the persistence context that tracks entities, and the lazy loading that fills collections. After them, we trigger the N+1 problem on this model.
Exercise
The Book entity declares @ManyToOne(fetch = FetchType.LAZY), and Author declares @OneToMany(mappedBy = "author") with no fetch attribute. Which of the two associations would be eager if you removed fetch = FetchType.LAZY from Book, and which stays lazy?
Show answer
Book.author would become eager, because the JPA default for @ManyToOne is EAGER. Author.books stays lazy, because the JPA default for @OneToMany is LAZY.
Exercise
You call author.getBooks().add(new Book("Draft")) on a managed author, without calling addBook or setAuthor, and then save the book. What value does the author_id column hold for the new row, and why?
Show answer
It is null. Book.author is the owning side of the association and the only side that writes the foreign key. Adding a book to the inverse collection Author.books does not set book.author, so Hibernate has nothing to write to author_id. Calling author.addBook(book) sets both sides.
Exercise
What would Hibernate generate if you removed mappedBy = "author" from @OneToMany on Author.books?
Show answer
It would treat books as a separate unidirectional association with its own owner, and create a join table (named author_books by default) holding author ids and book ids. The book.author_id column would still exist for Book.author, so the same relationship is stored in two places.