Skip to main content

The N+1 Problem, Fetch Joins, Entity Graphs and Batch Fetching

Learn The N+1 Problem, Fetch Joins, Entity Graphs and Batch Fetching (Phase 7 · Hibernate Performance Optimization (Essential), Hibernate) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

What is the N+1 query problem? • You run 1 query to load N parents, then N more queries (one per parent) to load a lazy association while iterating: N+1 round trips. With 1000 courses it means 1001 queries instead of 1 or 2: the most common Hibernate performance bug. • Causes: lazy collections/proxies accessed in a loop (or in toString /mapper/JSON serialisation), EAGER associations with JPQL (Hibernate loads the parent with your query, then each association with extra selects), Open Session In View hiding it until production. • Detect : enable SQL logging and look for repeating statements;...

More lessons in Phase 7 · Hibernate Performance Optimization (Essential)