Skip to content
Preptima
hardScenarioConceptMidSeniorStaff

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?

The repository call fetches parents in one query; the extra queries come later, when something touches a lazy association - usually the JSON serialiser, with open-session-in-view keeping the context alive so it succeeds silently. Diagnose by counting statements per request, then fix with a join fetch or entity graph, batch fetching, or a DTO projection.

4 min readUpdated 2026-08-16Target archetype: Enterprise Captive, Big Tech, Product Startup

Answer

Short answer

The repository method is not issuing the queries. It fetches the parent rows in one statement and returns entities whose collections are lazy proxies. The extra queries appear later, when something iterates those collections — almost always the JSON serialiser walking the object graph. Open-session-in-view keeps the persistence context open into the view layer, so each lazy load quietly succeeds instead of failing, and one clean line becomes N+1 statements.

Was this answer helpful?

Likely follow-ups

  • You add JOIN FETCH and now the page size is ignored and heap usage climbs. What happened?
  • Two collections on the same entity, both join fetched. What exception do you get and why?
  • Would setting FetchType.EAGER on the association fix this? What does it do to your other queries?
  • How do you decide between @EntityGraph and a hand-written JPQL query?
  • What breaks if you simply disable open-session-in-view tomorrow?

Related questions

Further reading