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, payments for each order triggers separate queries per association per order; serializing entities to JSON touches every lazy field.
  • Fixes:
    • @EntityGraph(attributePaths = {"lines", "customer"}) or join fetch queries for this endpoint.
    • hibernate.default_batch_fetch_size=50 to load associations in batches.
    • Return DTO projections instead of entities.
    • spring.jpa.open-in-view=false to 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).