Question
Eager vs Lazy Fetching in JPA: Trade‑off for Initial Latency vs N+1 Queries
Rin Echo
0 reputation · 01 Jun 2022, 01:42 UTC
26.3K views0
Goal
Determine which fetch strategy achieves the best balance between initial query latency and avoidance of N+1 queries for a complex entity graph.
Constraints & Uncertainty
Eager fetching inflates result sets and may degrade initial load times, while lazy fetching can trigger many round‑trips if associations are accessed in a loop. The optimal choice may depend on collection size, depth, and access patterns.
Trade‑off Considerations
- Initial latency vs. total round‑trips
- Result set size vs. N+1 query frequency
- Impact of @Fetch(FetchMode.SUBSELECT) and batch fetching
Open Questions
- For an entity with a large one‑to‑many collection, does eager fetching consistently deliver lower total execution time than lazy fetching?
- Can @Fetch(FetchMode.SUBSELECT) provide a middle ground that reduces N+1 queries without excessive round‑trips for deeply nested graphs?
- Which caching strategy (Ehcache vs Hazelcast) best complements lazy fetching to mitigate N+1 queries while keeping initial latency acceptable?