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) {3total += 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.
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:
| Association | Default |
|---|---|
@ManyToOne, @OneToOne | EAGER |
@OneToMany, @ManyToMany | LAZY |
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.
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=debuglogs every statement (spring.jpa.show-sql=trueprints them to stdout instead). Addlogging.level.org.hibernate.orm.jdbc.bind=tracein Hibernate 6 to see parameters. - Hibernate statistics:
spring.jpa.properties.hibernate.generate_statistics=truelogs 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;67@Test8void loadsOrdersWithLinesInOneQuery() {9// ... persist a few orders with lines, then:10em.flush();11em.clear(); // otherwise the persisted entities, lines already set, are returned and nothing lazy-loads12Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();13stats.setStatisticsEnabled(true);14stats.clear();1516orders.findByStatus(Status.OPEN).forEach(o -> o.getLines().size());1718assertThat(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.
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> {23// JOIN FETCH: one SQL join that initialises the collection4@Query("select o from Order o join fetch o.lines where o.status = :status")5List<Order> findWithLines(@Param("status") Status status);67// @EntityGraph: the same fetch plan on a derived query8@EntityGraph(attributePaths = {"customer", "lines"})9List<Order> findByStatus(Status status);1011// DTO projection: only the columns the screen needs, no entities12@Query("""13select new com.example.OrderSummary(o.id, c.name, count(l))14from Order o join o.customer c left join o.lines l15group by o.id, c.name""")16List<OrderSummary> summaries();17}1819record OrderSummary(Long id, String customer, Long lineCount) {}
join fetchloads parents and children in one statement. Useleft join fetchto keep orders without lines. In Hibernate 6 the duplicate parent rows a collection join produces are removed for you; Hibernate 5 neededdistinct.@EntityGraph(Spring Data's wrapper around a JPA entity graph) adds the joins to any repository method, includingfindAlland derived queries, without writing JPQL.- Batch fetching keeps loading lazy but loads many at once:
@BatchSize(size = 16)on the association or entity, orspring.jpa.properties.hibernate.default_batch_fetch_size=16for all of them. Touching the first uninitialised collection loads it for up to 16 owners with anin (...)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.
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):
LIMITon SQL rows would cut a parent's children in half, so Hibernate fetches every matching row and appliessetFirstResult/setMaxResults(or a Spring DataPageable) in memory, logging a "firstResult/maxResults specified with collection fetch; applying in memory" warning. Sethibernate.query.fail_on_pagination_over_collection_fetch=trueto make it an exception. The usual fix: page the ids first (select o.id from Order o ... order by ...with aPageable), thenjoin fetchthe orderswhere o.id in :ids(repeat theorder byin 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 hintorg.hibernate.limitInMemoryrestores the old behaviour. Paging the ids first still works on every version. MultipleBagFetchException: fetching twoListcollections 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
Setmakes 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 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.