Day 18 — JPA Performance Tuning & Batch Fetching¶
Daily Time Investment: 2.5 hours | Week: 3 | Phase: 3
Daily Schedule¶
| Segment | Duration | Activity |
|---|---|---|
| Core Theory | 45 min | N+1 diagnosis, JPQL JOIN FETCH, @BatchSize batch subselects, JPA 3.1 EntityGraph (fetchgraph vs loadgraph), scalar DTO projections |
| Book Reading | 30 min | Pro Persistence Ch11 (Native SQL, Stored Procedures, Entity Graphs) + Ch12 (L2 Caching) |
| Hands-On Lab | 75 min | Profile 20-node N+1 baseline (21 queries) → fix with JOIN FETCH (1 query) → @BatchSize (3 queries) → EntityGraph (1 query) → DTO projection (0 entity overhead) |
Files in This Day¶
-
Pro Persistence Ch11 — Advanced Queries
Native SQL queries (
createNativeQuery()),@NamedNativeQuery,@SqlResultSetMapping(@EntityResult,@FieldResult,@ColumnResult,@ConstructorResult), Stored Procedures (StoredProcedureQuery,@NamedStoredProcedureQuery), Entity Graphs (@NamedEntityGraph,@NamedAttributeNode, Fetch Graph vs Load Graph hints). -
Pro Persistence Ch12 — Advanced Topics (Caching)
Second-Level Cache (L2):
shared-cache-modeinpersistence.xml(ALL/NONE/ENABLE_SELECTIVE/DISABLE_SELECTIVE),@Cacheable,CacheRetrieveMode/CacheStoreModeruntime hints,CacheAPI (evict,evictAll,contains). -
Lab Guide — N+1 Diagnosis & Fetching Strategies
Hibernate
StatisticsServicecounts queries,JOIN FETCHeliminates 95% of queries,@BatchSize(10)halves remaining,EntityGraph(dynamic fetch plan without JPQL change), scalarrecordprojections with zero entity lifecycle overhead.
Prerequisites to Continue¶
New concepts not seen in Phase 1 or Phase 2
- N+1 Select Problem — loading N parent entities with
FetchType.LAZYand then accessing a child collection fires N additional SELECT queries; for N=20 nodes, that's 21 SQL statements instead of 1 - Hibernate
StatisticsService— JPA provider API that counts executed SQL statements per transaction; used to prove N+1 was eliminated; enabled viahibernate.generate_statistics=true @BatchSize(size=10)— Hibernate-specific annotation on a collection; instead of N individual SELECTs, usesWHERE id IN (?, ?, ..., ?)batch queries; for N=20, becomesceil(20/10) = 2batch queries instead of 20EntityGraph— JPA 3.1 standard; declares which associations to fetch eagerly at query time without modifying entityFetchTypeannotations; two hint types:fetchgraph(ONLY listed attributes are EAGER) vsloadgraph(listed are EAGER, unlisted inherit their static mapping)@NamedNativeQuery— pre-defined native SQL query stored on an entity; executed withem.createNamedQuery()same as JPQL but runs raw SQL against the database@SqlResultSetMapping— maps raw SQL result columns to entity classes or constructor projections when column names don't match JPA defaultsStoredProcedureQuery— JPA API for calling database stored procedures; supportsIN,OUT,INOUT, andREF_CURSORparameter modes