Introduction
Join fetch helps load related data in one go. It avoids extra database calls, making your app faster.
Jump into concepts and practice - no test required
Join fetch helps load related data in one go. It avoids extra database calls, making your app faster.
SELECT p FROM ParentEntity p JOIN FETCH p.childEntities WHERE p.id = :id
SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :orderId
SELECT c FROM Customer c JOIN FETCH c.address WHERE c.name = :name
This Spring Boot repository method uses join fetch to load a ParentEntity and its ChildEntity set in one query. This avoids multiple database calls when accessing children.
import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import org.springframework.stereotype.Repository; @Repository public class ParentRepository { @PersistenceContext private EntityManager em; public ParentEntity findByIdWithChildren(Long id) { return em.createQuery( "SELECT p FROM ParentEntity p JOIN FETCH p.childEntities WHERE p.id = :id", ParentEntity.class) .setParameter("id", id) .getSingleResult(); } } // Entities import jakarta.persistence.*; import java.util.Set; @Entity public class ParentEntity { @Id private Long id; private String name; @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<ChildEntity> childEntities; // getters and setters } @Entity public class ChildEntity { @Id private Long id; private String value; @ManyToOne @JoinColumn(name = "parent_id") private ParentEntity parent; // getters and setters }
Join fetch only works in JPQL or HQL queries, not in native SQL.
Use join fetch carefully to avoid loading too much data at once.
It helps prevent the "N+1 select problem" where many small queries slow down your app.
Join fetch loads related entities in one database query.
It improves performance by reducing extra queries.
Use it in JPQL with the JOIN FETCH keyword.
JOIN FETCH in Spring Boot JPA queries?JOIN FETCH doesJOIN FETCH tells JPA to load related entities eagerly in the same query instead of lazy loading them later.JOIN FETCH before the association path: JOIN FETCH p.children.SELECT p FROM Parent p JOIN FETCH p.children matches the correct syntax. The others misuse the order of keywords or use incorrect join types.SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id
JOIN FETCH to eagerly load the items collection along with the Order entity filtered by id.SELECT c FROM Customer c JOIN FETCH c.orders o WHERE o.status = 'PENDING'
orders with WHERE o.status = 'PENDING' can cause multiple rows per customer if they have multiple pending orders.Customer entities in the result list unless distinct is used.Author entities with their books and each book's publisher in one query. Which JPQL query correctly uses join fetch for this?JOIN FETCH a.books b and then JOIN FETCH b.publisher to fetch nested associations.