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

โ† Back to The N+1 query problem (JPA and Hibernate)

๐Ÿฝ๏ธ The N+1 query problem (JPA and Hibernate): cheat sheet

๐ŸŽจ The analogyA waiter who walks back to the kitchen once per diner for each side dish, instead of carrying one tray.
๐ŸŽ“ The regular explanationHow 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.
One query, then one per rowStep 4 of 4
Ticket spikeordkey select ... from orders: orders01 lkey select ... from order_line where order_id = 1: 1 lines12 lkey select ... from order_line where order_id = 2: 2 lines23 lkey select ... from order_line where order_id = 3: 3 lines345๐Ÿฝ๏ธTable 43 orders๐ŸคตWaiter1 + 3 queries๐Ÿง‘โ€๐ŸณKitchen1 + N trips
  1. The table orders, and the waiter makes one trip to the kitchen for all the main dishes. One ticket goes on the spike.
  2. The first diner asks for chips. The waiter walks back to the kitchen for that one bowl. A second ticket.
  3. Then the second diner asks, then the third. Each time, another walk to the kitchen and another ticket.
  4. Four trips for one table. With sixty diners it would be sixty-one trips, and the whole room would wait.
Lazy and eager loadingStep 4 of 4
๐Ÿฝ๏ธTable 4๐ŸคตWaiter1 + N anyway๐Ÿง‘โ€๐ŸณKitchen
  1. With the first way of working, the waiter brings only the main dish and leaves a ticket on the plate where the chips will go.
  2. Only when the diner asks for the chips does the ticket send the waiter back to the kitchen.
  3. With the second way, serving one diner, the waiter carries the main and its side together in a single trip.
  4. But for a whole table he brings all the mains, then still walks back once per diner for their side. Always bringing sides didn't save a single trip.
Spotting N+1Step 3 of 3
Ticket spikeordkey select ... from orders: orders01 lkey select ... from order_line where order_id = ?: 1 lines12 lkey select ... from order_line where order_id = ?: 2 lines23 lkey select ... from order_line where order_id = ?: 3 lines345๐Ÿง‘โ€๐Ÿ’ผManagertest fails๐ŸคตWaiter๐Ÿง‘โ€๐ŸณKitchen๐Ÿ”ข Tally card4 trips
  1. The waiter serves one table during a practice run. Every trip leaves a ticket on the spike, and the same ticket keeps coming back with a different diner on it.
  2. The tally card counts every trip, so nobody has to read the tickets one by one.
  3. The manager's rule says one table takes at most one trip. He checks the tally, sees four, and the practice run fails before real diners ever wait.
Four ways to fewer queriesStep 4 of 4
Ticket spikejoikey select o.*, l.* from orders o join order_line l on ...: join fetch0grakey entity graph: orders left join order_line: graph1in key select ... from order_line where order_id in (?, ?, ...): in (1..16)2in key select ... from order_line where order_id in (?, ?, ...): in (17..32)3dtokey select o.id, c.name, count(l.id) ... group by ...: dtoโœฆโœฆโœฆโœฆโœฆ45๐Ÿฝ๏ธTable 4๐ŸคตWaiterread-only DTOs๐Ÿง‘โ€๐ŸณKitchen
  1. The table says up front that everyone wants their sides. The waiter carries all the mains and all the sides on one tray. One trip, one ticket.
  2. This table always orders that way, so it's written on the order pad once. The waiter reads the pad and brings one full tray without being told.
  3. When the first diner asks for chips, the waiter brings chips for sixteen diners in one go. A handful of trips instead of sixty-one.
  4. If the table only wants to read the bill, the waiter fetches no dishes at all, just a printed list of names and prices.
When one tray is too muchStep 5 of 5
๐Ÿฝ๏ธTable 4๐ŸคตWaiter2 queries๐Ÿง‘โ€๐ŸณKitchen
  1. The table asks for only the first ten diners for now. With all the sides on one tray, the waiter carries out food for the whole room and picks out ten at the counter.
  2. Better to ask first who the ten diners are, then bring just their food on one tray.
  3. Now the table wants salads and drinks on the same tray, both as loose heaps. The waiter refuses before setting off, because he couldn't tell a real second helping from a repeat.
  4. With the sides labelled he'll carry them, but the kitchen plates every salad with every drink. Three of each makes nine plates per diner, and the tray groans.
  5. The fix is one kind of side per tray. Two light trips beat one overloaded tray.
LazyInitializationException and open-in-viewStep 4 of 4
๐Ÿ™‹Diners๐ŸคตWaiteropen-in-view=false๐Ÿง‘โ€๐ŸณKitchen
  1. The waiter serves the mains, and right after, his shift ends.
  2. A diner asks for chips. Nobody on shift can go to the kitchen, so the diner gets an angry "sorry, can't".
  3. This restaurant keeps the waiter on shift until the diners leave. The chips arrive, but with one hidden trip per diner, and a kitchen line stays tied up the whole time.
  4. Better to decide what the table needs while the waiter is still on shift, and bring it all on one tray.

๐Ÿงฉ Key questions

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?
Fifty-one: one for the mains, then one per diner. Each request for chips sends him back to the kitchen on his own, so it's one trip plus one per diner.
To save trips, someone tells the waiter to always bring the sides, whatever happens. What changes when the whole table orders?
He still walks back once per diner for their sides, just without being asked. Always bringing the sides only means he doesn't wait to be asked. Only telling him the whole order up front gets it onto one tray.
The table wants only the first ten diners served, and the waiter puts everyone's sides on the same tray. What goes wrong?
He brings the whole room's food and picks out ten at the counter. He can't tell where diner ten ends on a shared tray, so he takes everything. Asking who the ten are first, then fetching their food, fixes it.
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?
Each late request is still its own trip, now hidden, and a kitchen line stays tied up. Staying on shift hides the angry answer but not the trips. Better to decide what the table needs while he's still on shift.