Use @EntityGraph for Fetch Joins
Spring Data JPA supports @EntityGraph
to fetch associations in a single query:
@EntityGraph(attributePaths = {"courseModules"})
List<CourseEntity> findAll();
This tells Spring Data to generate a JOIN FETCH
under the hood.
Use JPQL with JOIN FETCH
If you're writing custom queries, use JOIN FETCH
to eagerly load associations:
@Query("SELECT c FROM CourseEntity c JOIN FETCH c.courseModules")
List<CourseEntity> findAllWithModules();
This avoids the N+1 problem by fetching all data in one query.
Avoid fetch = FetchType.EAGER
Using EAGER
by default can lead to unexpected behavior and performance issues. Prefer LAZY
and control fetching explicitly via queries or entity graphs.
Use @BatchSize (Hibernate-specific)
If you must use lazy loading, you can reduce the number of queries using batching:
@OneToMany(mappedBy = "courses", fetch = FetchType.LAZY)
@BatchSize(size = 10)
private Set<CourseModules> courseModules;
This tells Hibernate to fetch related entities in batches instead of one-by-one.