TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท jpa ยท hibernate ยท spring data ยท performance

The N+1 query problem (JPA and Hibernate)

How an ORM turns one query for a list of entities into one more query per entity when code touches a lazy or eager association, how to spot it, and how JOIN FETCH, entity graphs, batch fetching and DTO projections fix it.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ›’ Transactions and isolation๐Ÿ“‘ Database indexes๐Ÿ“ Spring transactions (@Transactional)

๐Ÿ–จ๏ธ Cheat sheet

One trip, then one more per diner

A table of six sits down and orders. The waiter walks to the kitchen and comes back with six main dishes. So far, so good: one trip.

Then the first diner asks, "Where are my chips?" The waiter walks back to the kitchen for one bowl of chips. Then the second diner asks for theirs, and the waiter walks back again. Six diners, six more walks. One trip for the mains, plus one trip per diner: seven trips where one tray would have done.

Each trip is short, but the walking adds up. With sixty diners it's sixty-one trips, and the whole room waits. That pattern has a name: the N+1 problem. One trip for the list, then N more, one for each diner.

Entities, associations and the 1 + N queries

An ORM such as Hibernate (the usual JPA provider in Spring Boot) maps each table to an @Entity class and each foreign key to an association field: @ManyToOne and @OneToOne for a single related entity, @OneToMany and @ManyToMany for a collection. You write Java that walks those fields, and the ORM decides when to run SQL.

1@Entity @Table(name = "orders")2class Order {3  @Id Long id;4  @Enumerated(EnumType.STRING) Status status;5  @ManyToOne(fetch = FetchType.LAZY) Customer customer;6  @OneToMany(mappedBy = "order") List<OrderLine> lines = new ArrayList<>();7  @OneToMany(mappedBy = "order") List<Tag> tags = new ArrayList<>();8}

The N+1 select problem is what happens when code loads a list of N entities with one query, then touches an association on each of them and the ORM loads it with a separate query each time:

1List<Order> orders = orderRepository.findAll();      // 1 query: select ... from orders2for (Order o : orders) {3  total += o.getLines().size();                       // N queries: select ... from order_line where order_id = ?4}

Every one of those queries is cheap on its own, often an index lookup on order_line.order_id (if that foreign key is indexed; see database indexes and query planning). The cost is the round trips: N network hops, N statement executions, N result sets. It grows linearly with the data, so it's invisible with ten test rows and slow with ten thousand.

One query, then one per row4 steps
Ticket spike012345๐Ÿฝ๏ธTable 4๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen
Press play and watch it happen!

Bring it now, or bring it when asked

The waiter can work two ways. In the first, he brings only the mains and puts a little ticket on each plate: "chips, still in the kitchen". Nobody waits for chips they don't want. But when a diner does ask, that ticket sends him back to the kitchen. Fetching only when someone asks is called lazy.

In the second, he always brings the sides too, whether anyone wants them or not. For one diner that's fine: he carries the main and the chips together. But for a whole table, this waiter has a habit: he brings all the mains first, then still walks back once per diner for their sides, before anyone has even asked. Always bringing the sides doesn't mean one tray. It only means he never waits to be asked.

Lazy and eager loading

Every association has a FetchType. The JPA defaults are:

AssociationDefault
@ManyToOne, @OneToOneEAGER
@OneToMany, @ManyToManyLAZY

Lazy: Hibernate puts a placeholder in the field: a proxy for a single entity, a PersistentBag or PersistentSet for a collection. The first time code touches it (other than reading a proxy's id), Hibernate runs a query to load it, using the current persistence context. Lazy is a promise to load later, one association at a time, so a loop over N entities produces N loads.

Eager: the association must be loaded with its owner. em.find(Order.class, 7) can do that with a SQL join in one statement. But a JPQL or Spring Data query such as select o from Order o is translated as written: Hibernate runs it, then sees eager associations it hasn't loaded and issues a secondary select for each one (each distinct customer, for example). So EAGER on a list query is N+1 too, and every query that loads orders pays for it.

That's why the common advice is: map every association LAZY (add fetch = FetchType.LAZY to @ManyToOne and @OneToOne), and decide per use case what to load up front.

Lazy and eager loading4 steps
๐Ÿฝ๏ธTable 4๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen
Press play and watch it happen!

Counting the trips

You can't fix trips you can't see. So the kitchen keeps a ticket spike: every time the waiter comes in, his ticket goes on the spike. At the end of the evening the manager counts them. One table, sixty tickets? Something's wrong.

A careful manager goes further and sets a rule before opening: "a table's order takes one trip". If the waiter makes more during practice, the practice run fails, long before real diners have to wait.

Spotting N+1

The same query shape repeated with a different id is the signature. Ways to see it:

  • SQL logging: logging.level.org.hibernate.SQL=debug logs every statement (spring.jpa.show-sql=true prints them to stdout instead). Add logging.level.org.hibernate.orm.jdbc.bind=trace in Hibernate 6 to see parameters.
  • Hibernate statistics: spring.jpa.properties.hibernate.generate_statistics=true logs a per-session summary including how many JDBC statements were prepared and executed.
  • Count queries in tests: assert the number of statements for a use case, so a regression fails the build.
1@DataJpaTest2class OrderQueriesTest {3  @Autowired OrderRepository orders;4  @Autowired TestEntityManager em;5  @Autowired EntityManagerFactory emf;6 7  @Test8  void loadsOrdersWithLinesInOneQuery() {9    // ... persist a few orders with lines, then:10    em.flush();11    em.clear();                                        // otherwise the persisted entities, lines already set, are returned and nothing lazy-loads12    Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();13    stats.setStatisticsEnabled(true);14    stats.clear();15 16    orders.findByStatus(Status.OPEN).forEach(o -> o.getLines().size());17 18    assertThat(stats.getPrepareStatementCount()).isEqualTo(1);19  }20}

A JDBC proxy library that wraps the DataSource and counts statements does the same job independently of Hibernate. APM tools and slow-request traces also show it: one request, hundreds of near-identical queries.

Spotting N+13 steps
Ticket spike012345๐Ÿง‘โ€๐Ÿ’ผManager๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen๐Ÿ”ข Tally card
Press play and watch it happen!

One tray for the whole table

The fix is to tell the waiter, before he leaves the table, what everyone will need. Then he carries the mains and all the sides on one tray: one trip.

If the table always orders the same way, write it on the order pad once, "this table: mains with sides", and he never has to be told again. Or, without telling him anything up front, the waiter learns a habit: when one diner asks for chips, he brings chips for the next sixteen diners too. Sixty diners then take five trips instead of sixty-one. And if the table only wants to read the bill, he doesn't fetch dishes at all: he brings a printed list with just the names and prices.

Fixes: fetch joins, entity graphs, batches and projections

Choose the fetch plan per use case, at query time:

1interface OrderRepository extends JpaRepository<Order, Long> {2 3  // JOIN FETCH: one SQL join that initialises the collection4  @Query("select o from Order o join fetch o.lines where o.status = :status")5  List<Order> findWithLines(@Param("status") Status status);6 7  // @EntityGraph: the same fetch plan on a derived query8  @EntityGraph(attributePaths = {"customer", "lines"})9  List<Order> findByStatus(Status status);10 11  // DTO projection: only the columns the screen needs, no entities12  @Query("""13      select new com.example.OrderSummary(o.id, c.name, count(l))14      from Order o join o.customer c left join o.lines l15      group by o.id, c.name""")16  List<OrderSummary> summaries();17}18 19record OrderSummary(Long id, String customer, Long lineCount) {}
  • join fetch loads parents and children in one statement. Use left join fetch to keep orders without lines. In Hibernate 6 the duplicate parent rows a collection join produces are removed for you; Hibernate 5 needed distinct.
  • @EntityGraph (Spring Data's wrapper around a JPA entity graph) adds the joins to any repository method, including findAll and derived queries, without writing JPQL.
  • Batch fetching keeps loading lazy but loads many at once: @BatchSize(size = 16) on the association or entity, or spring.jpa.properties.hibernate.default_batch_fetch_size=16 for all of them. Touching the first uninitialised collection loads it for up to 16 owners with an in (...) list (or a single array parameter on databases such as PostgreSQL), so N+1 becomes 1 + N/16. It also works when you can't change the query.
  • DTO projections (constructor expressions, interface or record projections) read only the columns you need. Nothing is managed, so nothing is lazy, and no dirty checking runs. Best for read-only screens and APIs.
Four ways to fewer queries4 steps
Ticket spike012345๐Ÿฝ๏ธTable 4๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen
Press play and watch it happen!

When the tray gets too heavy

One tray has limits. Say the table says, "only serve the first ten diners for now". With everyone's sides on one tray, the kitchen can't tell where diner ten ends, so the waiter carries the whole room's food out and sorts out the first ten at the counter. Better: first ask who the first ten are, then fetch their food on one tray.

Two kinds of side on the same tray is worse. If each diner has three salads and three drinks, the kitchen plates every salad with every drink: nine pairings per diner. When those sides come in loose, unlabelled heaps, the waiter refuses outright, because it can't tell a real second helping from a repeat. Carry one kind of side per tray instead.

Fetch join pitfalls

  • Pagination with a collection fetch (Hibernate 6 and 7 before 7.4, i.e. Spring Boot 3.x and 4.0): LIMIT on SQL rows would cut a parent's children in half, so Hibernate fetches every matching row and applies setFirstResult/setMaxResults (or a Spring Data Pageable) in memory, logging a "firstResult/maxResults specified with collection fetch; applying in memory" warning. Set hibernate.query.fail_on_pagination_over_collection_fetch=true to make it an exception. The usual fix: page the ids first (select o.id from Order o ... order by ... with a Pageable), then join fetch the orders where o.id in :ids (repeat the order by in the second query). Batch fetching also pages correctly, since the parent query has no collection join. Since Hibernate 7.4 (Spring Boot 4.1) the limit is pushed into a subquery on every supported database except Sybase ASE, so the page is applied in SQL; the query hint org.hibernate.limitInMemory restores the old behaviour. Paging the ids first still works on every version.
  • MultipleBagFetchException: fetching two List collections without @OrderColumn (bags: unordered, duplicates allowed) in one query fails with "cannot simultaneously fetch multiple bags", because Hibernate couldn't tell real duplicates from join duplicates.
  • Cartesian products: switching those fields to Set makes the exception go away but not the problem. Two collection joins return lines ร— tags rows per order, which can be far more data than N+1 ever moved. Fetch one collection per query (the persistence context stitches them onto the same entities), or use batch fetching for the second.

Joining any number of @ManyToOne associations is safe: they don't multiply rows.

When one tray is too much5 steps
๐Ÿฝ๏ธTable 4๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen
Press play and watch it happen!

When the waiter's shift is over

The waiter only goes to the kitchen while he's on his shift. If his shift ends right after he serves the mains and a diner then asks for chips, nobody can fetch them, and the diner gets an angry "sorry, can't" instead.

Some restaurants solve that by keeping the waiter on shift until the diners walk out the door. No more angry "sorry, can't", but every late request still means a separate trip, so the trips are back, now hidden. And a waiter on a long shift keeps a kitchen line tied up the whole time. Better: decide what the table needs while the waiter is still on shift, and bring it on one tray.

LazyInitializationException and open-in-view

A lazy association can only load while its persistence context is open, which with Spring's @Transactional means until the service method's transaction ends (see Spring transactions). Touch it afterwards, in a controller, a JSON serialiser or a view, and Hibernate throws LazyInitializationException (the message ends in "no session").

Spring Boot hides that by default: spring.jpa.open-in-view is true, which, in a servlet web app, registers an OpenEntityManagerInViewInterceptor that keeps the EntityManager open for the whole web request. Boot logs a startup warning when you haven't set the property explicitly. With it on:

  • lazy loads after the service returns just work, so N+1 moves into Jackson or the template, where nobody looks;
  • those loads run outside any transaction (normally auto-commit);
  • the request holds a database connection until the response is written, which can exhaust the connection pool under load.

Many teams set spring.jpa.open-in-view=false and fix each LazyInitializationException it reveals by loading what the caller needs inside the service: a fetch join, an @EntityGraph, or a DTO. Avoid FetchType.EAGER and hibernate.enable_lazy_load_no_trans as fixes: both bring N+1 back.

LazyInitializationException and open-in-view4 steps
๐Ÿ™‹Diners๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the waiter's evening as real Java code: the mains come on one trip, and the sides stay in the kitchen until someone asks. Pick a label, then tap the line where that happens. Can you find all four?

Tap the line where you see: The one trip for the mains.

0 of 4 placed

๐Ÿงฉ Finish the code

Now fix the waiter's habits yourself. A diner's drink should only come out if someone asks for it. Each diner's main and chips must come on one tray, and a diner who ordered no chips still gets their main. The salads can't share that tray, so they should come out sixteen diners at a time. Nobody keeps the waiter on shift for you here, so the shift must cover the whole job. Pick the right piece of code for each gap.
  1. 1 Bring a diner's drink only when they ask for it
  2. 2 Bring the salads for sixteen diners whenever one asks
  3. 3 Put the chips on the same tray, and keep tables with no chips
  4. 4 Keep the waiter on shift for the whole job
1@Entity @Table(name = "orders")2class Order {3  @Id Long id;4  @ManyToOne(fetch = 1) Customer customer;5  @OneToMany(mappedBy = "order") List<OrderLine> lines = new ArrayList<>();6  @OneToMany(mappedBy = "order") 27  List<Tag> tags = new ArrayList<>();8}9 10interface OrderRepository extends JpaRepository<Order, Long> {11  @Query("select o from Order o 3 where o.status = :status")12  List<Order> findWithLines(@Param("status") Status status);13}14 15416int countLinesAndTags(Status status) {17  var orders = repo.findWithLines(status);18  return orders.stream().mapToInt(o -> o.getLines().size() + o.getTags().size()).sum();19}
0 of 4 gaps filled

๐Ÿงช Debug it for real

  • ๐ŸŒThe open orders report got slowThe waiter brings the list of open tables in one trip, then walks back to the kitchen for every table's guest card and dishes. The more tables are open, the slower the room gets. Make it one trip.Java 21Hibernate 6H2JUnit 5intermediate25 min

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about The N+1 query problem (JPA and Hibernate), told the same way as the story.
  1. The waiter brings the mains for 50 diners in one trip, then each diner asks for chips. How many trips does he make in total?
  2. To save trips, someone tells the waiter to always bring the sides, whatever happens. What changes when the whole table orders?
  3. The table wants only the first ten diners served, and the waiter puts everyone's sides on the same tray. What goes wrong?
  4. A restaurant keeps the waiter on shift until the diners leave, so late requests for chips never get a "sorry, can't". What's the catch?
Answer every question to check.Passing marks The N+1 query problem (JPA and Hibernate) as done.
Got the hang of The N+1 query problem (JPA and Hibernate)? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—ƒ๏ธ Spring and databasesStep 6 of 7

โ† Previous on the path๐Ÿš• Connection poolingNext on the path โ†’๐Ÿงญ Query planning and EXPLAIN