Video in progress

What is the N+1 problem?

List<Author> authors = authorRepo.findAll();
for (Author a : authors) {
    System.out.println(a.getName() + ": " + a.getBooks().size());
}

You fetch N main records with one query, then read the related data for each of them with a separate query. The result is 1 + N SELECTs; for 1000 records that means 1001 queries.

📖 Answer

In the code above, the first line sends one SELECT. Then getBooks() inside the loop opens the lazy collection for each author, one more SELECT each. With 300 authors, that's 301 queries.

On a local database you don't notice: each query takes 1 ms. On prod, if each one takes 3-5 ms over the network, the page waits a second or two.

How to spot it:

  • spring.jpa.show-sql=true or org.hibernate.SQL=DEBUG: you see a run of identical SELECTs in the logs;
  • Hibernate statistics (hibernate.generate_statistics=true): the number of queries;
  • libraries that assert the query count in tests.

Fixes:

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

or @EntityGraph(attributePaths = "books"), or @BatchSize(size = 50) on the collection. The last one cuts N queries down to N/50.

One note: EAGER doesn't save you from N+1 either. Most of the time it just hides it.