Java core learning path Level 2 This level · 22 of 29
Medium java spring

Fetch one hundred orders, call getItems on each?

The 30 second answer

Classic N-plus-one: one query for the orders plus one query per order for items when the association is lazy. Fix it with join fetch or EntityGraph, watch pagination with collection fetches because Hibernate may paginate in memory, use batch fetching, or write a DTO query. Detect it with SQL logging, Hibernate statistics, or a query-count assertion in tests.

Could you say this in an interview?

Classic N+1: 1 query for orders + 100 for items (lazy). Fix: JOIN FETCH / @EntityGraph (watch pagination + collection fetch: Hibernate paginates in memory), @BatchSize / hibernate.default_batch_fetch_size (loads in IN-batches), or a DTO query. Detect via SQL logging/Hibernate statistics or a query-count assertion in tests.

Sources (2)
  1. Hibernate User Guide — Fetching & batch fetchingdocs.jboss.org
  2. Spring Data JPA — @EntityGraphdocs.spring.io
Previous
Next