jpa
Explain the N+1 Query Problem and how to fix it.
What is it?
Occurs when you fetch a list of N objects, and for each object, a separate query is executed to fetch a related detail (e.g., fetching 10 Orders and then 10 separate queries for each Order's Customer).
How to Fix:
- Join Fetch: Use
JOIN FETCHin JPQL (SELECT o FROM Order o JOIN FETCH o.customer). - Entity Graph: Use
@EntityGraphto define which attributes should be fetched eagerly for a specific query. - Batch Size: Use
@BatchSizeto fetch related entities in larger chunks.