mediumConceptScenarioMidSeniorStaff
This endpoint logs one query per row. Why are you seeing N+1 queries, and how do you fix them?
6 min readUpdated 2026-08-15
Answer
Short answer
You get N+1 when one query loads N rows and something later dereferences a lazy association on each of them, firing a select apiece. Fix it per call site with join fetch, an entity graph, or batch fetching - not by changing mappings to EAGER.
Was this answer helpful?
Likely follow-ups
- How would you page over authors and still load their books in a bounded number of queries?
- What does spring.jpa.open-in-view do, and why does leaving it enabled hide this class of bug until production?
- When can you touch a lazy @ManyToOne without hitting the database at all?
- Why does join-fetching two List collections in one query fail, and what changes if one of them is a Set?
Related questions
- A Spring Data repository method looks like one clean line, but the endpoint issues several hundred queries per request. How do you diagnose the N+1, and what would you actually change?hardAlso on n-plus-one and hibernate4 min
- Nobody called save, but the UPDATE still went to the database. Explain how that happened.mediumAlso on jpa and hibernate5 min
- You pass a thousand new entities to saveAll and the database sees a thousand separate inserts. How do you get them batched?hardAlso on jpa and hibernate5 min
- Your lazy-loading proxy works until someone calls equals or getClass on it. What breaks, and how do you design a proxy that survives it?hardAlso on lazy-loading and hibernate5 min