The 30 second answer
I look at SQL logs or traces and see one query for the list followed by one query per item, which is the N+1 pattern. I fix it with a fetch join or an entity graph for that use case, or batch fetching so related rows load in groups. Then I add a test that asserts the number of queries, so it does not come back.
I turn on SQL logging or look at traces, and I see one query for the list and then one per row. In Hibernate I fix it per use case with a join fetch or an entity graph, or I set a batch size so it loads associations in one IN query. I keep mappings lazy by default.
Alternate interview scenarios
"Write the fix on the whiteboard: a product listing loads 48 products, then each product's brand and variants."
The bad version is a repository call for the list followed by lazy loading inside the loop, which sends 1 query for the products plus up to 48 for brands and 48 for variants. Three fixes, each with a cost:
// 1. Fetch join for a to-one association: one SQL join, safe with pagination
@Query("select p from Product p join fetch p.brand where p.category.id = :cat")
List<Product> findWithBrand(@Param("cat") long cat, Pageable page);
// 2. Entity graph for the same use case, without writing JPQL (Spring Data JPA)
@EntityGraph(attributePaths = {"brand"})
List<Product> findByCategoryId(long cat, Pageable page);
// 3. Batch fetching for a collection: variants load in IN (...) groups
@OneToMany(mappedBy = "product")
@BatchSize(size = 50)
private List<Variant> variants;The trap is fetch-joining a collection together with pagination. The Hibernate guide says that then "the limit must be applied in-memory instead of on the database", and hibernate.query.fail_on_pagination_over_collection_fetch (default false) turns that into an error. So page on the parent with a to-one fetch join, and load collections with batch fetching or a second query on the page's IDs. hibernate.default_batch_fetch_size sets a global default; by default Hibernate batches only associations annotated with @BatchSize.
"The ORM is fine, but the search API calls the pricing service once per product on the result page."
That's the same N+1 across a network. Use the pricing service's bulk endpoint with all 48 IDs, run independent calls in parallel, or put prices in the search document if slight staleness is acceptable.
Sources (4)
- Hibernate 6.6 User Guide: Dynamic fetching (join fetch, entity graphs)docs.jboss.org
- Hibernate 6.6 User Guide: Batch fetchingdocs.jboss.org
- Hibernate 6.6 User Guide: Query settings (fail_on_pagination_over_collection_fetch)docs.jboss.org
- Spring Data JPA reference: Query methods (configuring fetch and load graphs with @EntityGraph)docs.spring.io