Spring Boot JPA @EntityGraph, @NamedEntityGraph, and JOIN FETCH – Complete Guide with Examples
When working with Spring Boot JPA, the N+1 query problem can impact performance due to lazy loading. To optimize queries and fetch related entities efficiently, JPA provides @EntityGraph, @NamedEntityGraph, and JOIN FETCH. This guide walks you through their usage with practical examples, helping you write efficient, high-performance database queries in Spring Boot.
1. Introduction
When working with JPA and Hibernate, N+1 query issues often arise due to lazy loading.
- @NamedEntityGraph and @EntityGraph provide a way to fetch related entities efficiently.
- JOIN FETCH is a JPQL technique that helps load associated entities in a single query.
2. Create a Spring Boot Project
You can use Spring Initializr with:
- Spring Boot 3+
- Dependencies: Spring Web, Spring Data JPA, Lombok, H2 Database
3. Define JPA Entities
Department
Entity (OneToMany with Employee)
Employee
Entity (ManyToOne with Department)
4. Repository Layer
Using @EntityGraph (Annotation on Query Method)
✅ This ensures employees are fetched without lazy loading.
Using @NamedEntityGraph (Defined in Entity)
✅ This will use NamedEntityGraph defined in the Department
entity.
Using JOIN FETCH in JPQL
✅ This ensures Department & Employees are loaded in one query.
5. Service Layer
6. Controller Layer
7. Testing Queries in Logs
Enable SQL logging in application.properties
:
- Without
@EntityGraph
, lazy loading causes multiple queries. - With
@EntityGraph
,JOIN FETCH
, orNamedEntityGraph
, only one optimized query is used.
8. Summary of Best Practices
9. Conclusion
- If using Spring Data JPA methods, prefer
@EntityGraph
. - If using JPQL, use
JOIN FETCH
for optimized queries. - If using repeated queries, define
@NamedEntityGraph
.