Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 66 ยท Data Access

Entity Relationships and the N+1 Problem

Map OneToMany, ManyToOne and ManyToMany in Spring Boot, understand lazy and eager fetching, and fix the N+1 query problem with join fetch and entity graphs.

Real data is connected. An author has books, a book has tags, an order has lines. JPA lets you express those links as fields: an Author object holds a list of Book objects, and Hibernate loads the rows behind the scenes. That is convenient, and it hides the single most common performance problem in Spring applications: you ask for 100 authors and quietly send 101 queries to the database.

This lesson maps the three relationship types, explains the loading rules (LAZY and EAGER), demonstrates the N+1 problem with a query counter, and shows the fixes: join fetch, entity graphs, batch fetching and DTO projections. Entity basics are in Spring Data JPA Repositories, and a fuller mapping tour is in Entity Relationships.

The real JPA code is read-only, because Hibernate cannot run on this site. The runnable stand-ins use real H2 and plain JDBC with a query counter, which is the quickest way to feel the problem. The numbers you see are exactly the numbers Hibernate would produce.

The three relationship types

Many-to-one is the most important one: many books belong to one author. The book table holds the foreign key author_id.

One-to-many is the same relationship seen from the other side: one author has many books. In a bidirectional mapping, one side owns the relationship (the side with the foreign key), and the other side declares mappedBy.

Many-to-many needs a join table: a book can have many tags and a tag can mark many books.

Java
@Entity
class Author {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books = new ArrayList<>();

    void addBook(Book book) {            // keep both sides in step
        books.add(book);
        book.setAuthor(this);
    }
}

@Entity
class Book {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "author_id")
    private Author author;                // owning side: holds the foreign key

    @ManyToMany
    @JoinTable(name = "book_tag",
        joinColumns = @JoinColumn(name = "book_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private Set<Tag> tags = new HashSet<>();
}

A few rules keep these mappings healthy:

  • Only the owning side writes the foreign key. If you add a book to author.getBooks() but never call book.setAuthor(...), nothing is saved. The helper method addBook prevents that mistake.
  • cascade = ALL means saving or deleting the author also saves or deletes its books. Use it for true parent-child ownership (an order and its lines), not between independent things (a book and its tags).
  • orphanRemoval = true deletes a child when you remove it from the parent's list.
  • Prefer Set for many-to-many and keep collections initialized so they are never null.
  • Do not print entities with toString that walks both directions; a book printing its author printing its books loops forever. Return DTOs from controllers anyway.

Reading the mapping

Owning side Holds the foreign key. Writes it.
mappedBy side A mirror. Reads only.
Cascade Passes save and delete to children.
Orphan removal Deletes children you remove.
1 / 2

Lazy and eager loading

Eager loading fetches the related data together with the owner. Lazy loading puts a placeholder in the field and runs a query only when your code first touches it. JPA's defaults are EAGER for @ManyToOne and @OneToOne, and LAZY for collections. The sensible rule is: make everything LAZY (explicitly set fetch = LAZY on @ManyToOne and @OneToOne) and decide per query what to load. Eager mappings cannot be turned off for a single query; lazy ones can be loaded when needed.

Lazy loading has a catch. The placeholder needs an open persistence session to run its query. If you touch it after the transaction has ended, Hibernate throws a LazyInitializationException. The stand-in below makes the rule visible with a lazy list that loads from H2 on first access, and refuses once its "session" is closed.

Java Lazy loading and a closed session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The author arrives without its books; the books load on first touch; and a second author whose session ended cannot load them at all. Spring Boot has a feature that hides this error, open-in-view (spring.jpa.open-in-view, on by default), which keeps the session open until the web response is written. It sounds friendly, but it holds a database connection during view rendering and turns every lazy touch in a controller into a hidden query. Most teams switch it off and load exactly what a request needs, which is the topic of the rest of this lesson. The Transactions lesson comes back to it.

The N+1 problem

Here is the classic code. It looks innocent:

Java
List<Author> authors = authorRepository.findAll();           // query 1
for (Author author : authors) {
    System.out.println(author.getName() + ": " + author.getBooks().size());   // one query per author
}

findAll() runs one query for the authors. Then each getBooks() touches a lazy collection and runs another query. With N authors you get 1 + N queries. With 5 authors nobody notices; with 5,000 authors and a database on another machine, the page crawls, and the problem never shows up in a unit test with three rows.

Run the numbers yourself. The stand-in below counts queries for three strategies on the same data.

Java Counting queries: N+1 versus join versus batch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Five authors cost six queries the naive way, one with a join and two with batching, while the result is identical. Now the real-world tools for the same three strategies.

Fixing N+1

Join fetch loads the collection in the same query:

Java
interface AuthorRepository extends JpaRepository<Author, Long> {

    @Query("select distinct a from Author a left join fetch a.books")
    List<Author> findAllWithBooks();
}

Entity graphs express the same wish without JPQL, and you can attach one to a derived query:

Java
interface AuthorRepository extends JpaRepository<Author, Long> {

    @EntityGraph(attributePaths = "books")
    List<Author> findByNameStartingWith(String prefix);
}

Batch fetching keeps lazy loading but loads many collections per query, as in the IN strategy of the stand-in. Set it once for the whole application, or per collection with @BatchSize(size = 50):

YAML
spring:
  jpa:
    properties:
      hibernate:
        default_batch_fetch_size: 50

DTO projections avoid entities completely when you only need a few values, and they are usually the best choice for read-only screens:

Java
record AuthorBookCount(String name, long books) {}

@Query("""
    select new com.example.AuthorBookCount(a.name, count(b))
    from Author a left join a.books b
    group by a.name
    """)
List<AuthorBookCount> countBooksPerAuthor();

Choosing between them:

  • Need the entities and will modify them: join fetch or an entity graph.
  • Need entities and many collections, or a paged list: batch fetching.
  • Read-only screen or report: a DTO projection with exactly the columns you need.

Two traps with join fetch

  1. Paging with a collection fetch. If you add Pageable to a query that join-fetches a collection, Hibernate cannot apply LIMIT in SQL, because one author spans several rows. It loads everything and pages in memory, and logs a warning saying so. Page the parents first and then load their children in a second query, or use batch fetching.
  2. Fetching several lists at once. Join-fetching two List collections in one query throws MultipleBagFetchException (and would multiply the rows in a Cartesian product anyway). Use Set, or fetch one collection per query.

Catching N+1 early

Looking is the cure. In development:

  • Log SQL with logging.level.org.hibernate.SQL=debug, then read it. A page that prints the same statement thirty times is your answer.
  • Turn on Hibernate statistics (spring.jpa.properties.hibernate.generate_statistics=true) and look at the "statements executed" count.
  • In tests, assert on the number of statements for important endpoints, so a future change that adds a hidden query turns the build red. Testing the Data Layer shows how tests are set up.

Treat every getX() of a lazy collection inside a loop as a query. If you cannot say how many queries a request runs, count them once with the SQL log before you ship.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a bidirectional OneToMany/ManyToOne mapping, which side writes the foreign key?

    The owning side holds the foreign key column and is the one Hibernate uses when saving. The mappedBy side is a read-only mirror, so keep both sides in sync with a helper method.
  2. 2. What are the JPA default fetch types for @ManyToOne and @OneToMany?

    @ManyToOne and @OneToOne default to EAGER; collection mappings default to LAZY. Most teams set @ManyToOne(fetch = LAZY) explicitly.
  3. 3. A page lists 200 authors and prints each author's book count, and the log shows 201 SQL statements. What is this called?

    One query loaded the authors and one extra query per author loaded the lazy collection, giving 1 + N statements. Join fetch, entity graphs, batching or a DTO projection fix it.
  4. 4. Why is combining join fetch on a collection with a Pageable a problem?

    Joining a collection multiplies rows per parent, so SQL LIMIT would cut parents in half. Hibernate loads everything and pages in memory, which defeats the purpose.

Summary

  • Many-to-one is the foreign-key side that owns the mapping; one-to-many with mappedBy mirrors it; many-to-many needs a join table.
  • Keep both sides of a bidirectional link in sync with helper methods, and use cascade and orphan removal only for real parent-child ownership.
  • Make associations LAZY and choose what to load per query.
  • A lazy association needs an open session; touching it afterwards throws LazyInitializationException, and open-in-view only hides that error.
  • N+1 means one query for the parents plus one per parent; fix it with join fetch, entity graphs, batch fetching or DTO projections.
  • Beware paging combined with collection fetches and fetching multiple lists at once.
  • Read the SQL log and count statements to catch N+1 before production.

Next: Transactions with @Transactional.