Category: java
Understanding Fetch Types
Published on 24 Jul 2026
Explanation
Spring Data JPA provides two fetch strategies: Lazy Loading and Eager Loading. Lazy Loading retrieves related data only when it is accessed, while Eager Loading fetches related entities immediately. Choosing the appropriate strategy improves application performance.
Code:
@OneToMany(mappedBy = "student", fetch = FetchType.LAZY) private List<Course> courses; @ManyToOne(fetch = FetchType.EAGER) private Department department;
Explanation
Lazy Loading reduces memory usage and database queries by loading related entities only when required. Eager Loading retrieves all related data in a single operation, which is useful when associated data is always needed but may increase query execution time.
Code:
FetchType.LAZY β Load when accessed FetchType.EAGER β Load immediately
Explanation
The N+1 Query Problem occurs when JPA executes one query to fetch parent entities and then executes an additional query for each related child entity. This results in excessive database calls and poor application performance.
Code:
1 Query β Students + N Queries β Courses ------------------- Total = N + 1 Queries
Explanation
Use JPQL FETCH JOIN to retrieve parent and child entities in a single SQL query. This eliminates unnecessary database calls and significantly improves performance when loading related data.
Code:
@Query("SELECT s FROM Student s JOIN FETCH s.courses")
List<Student> findAllWithCourses();
Explanation
Prefer Lazy Loading for most relationships, use Fetch Join or EntityGraph when related data is required, avoid unnecessary Eager Loading, and enable pagination to reduce memory usage and improve database performance in large applications.
Code:
@EntityGraph(attributePaths = "courses") List<Student> findAll();