Java Developer interview question

How do you avoid JPA N+1 queries?

N+1 occurs when one query loads parents and subsequent lazy access issues one query per parent; solve it with a fetch join, entity graph, batch fetching, or a projection chosen for the use case.

Direct answer

What a strong answer covers

How it works

Lazy associations are loaded on first access, so iterating over a hundred orders and reading order.getCustomer() issues one query for the orders and a hundred more for the customers. The fix depends on the use case: a JOIN FETCH in JPQL or an @EntityGraph loads the association in the same query, @BatchSize or hibernate.default_batch_fetch_size turns the hundred queries into a few IN queries, and a DTO projection avoids entities entirely for read-only screens. Turning on SQL logging or Hibernate statistics in tests exposes the problem before production does.

Example

A report listing orders with customer names went from 101 queries to one after changing the repository method to @Query("select o from Order o join fetch o.customer"). For an endpoint that needs orders plus two collections, two fetch joins would produce a cartesian product, so the second collection uses batch fetching instead.

Common mistakes

  • Switching everything to EAGER fetching and loading the whole object graph on every query.
  • Fetch-joining multiple collections and multiplying rows.
  • Detecting the problem only from production latency instead of asserting query counts in tests.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Java Developer interview questions