A Spring Data JPA endpoint returning 50 orders issues 2,000 SQL queries. Explain why and how you fix it.
Short answer
Lazy associations are loaded one by one when accessed (N+1 problem), often during JSON serialization or with open-session-in-view. Fix with fetch joins or entity graphs for the specific use case, batch fetching, or DTO projections, disable open-in-view, and add query-count assertions in tests.
Detailed answer
- Cause: loading orders (1 query) then accessing
lines,customer,paymentsfor each order triggers separate queries per association per order; serializing entities to JSON touches every lazy field. - Fixes:
@EntityGraph(attributePaths = {"lines", "customer"})orjoin fetchqueries for this endpoint.hibernate.default_batch_fetch_size=50to load associations in batches.- Return DTO projections instead of entities.
spring.jpa.open-in-view=falseto surface lazy loading in the right layer.
- Guard: tests asserting query counts; Hibernate statistics in staging.
What the interviewer expects
Root cause clarity and multiple remedies with trade-offs (fetch join + pagination issues, cartesian products).
Common mistakes to avoid
Switching everything to EAGER (causes over-fetching everywhere).