0
0
Spring Bootframework~5 mins

Join fetch for optimization in Spring Boot

Choose your learning style9 modes available
Introduction

Join fetch helps load related data in one go. It avoids extra database calls, making your app faster.

When you want to get an object and its related objects together.
When you want to avoid slow performance caused by many small database queries.
When you have a parent-child relationship and want to load both at once.
When you want to reduce the number of database trips in your app.
When you use JPA or Hibernate and want to optimize data fetching.
Syntax
Spring Boot
SELECT p FROM ParentEntity p JOIN FETCH p.childEntities WHERE p.id = :id
Use JOIN FETCH in JPQL to load related entities eagerly in one query.
Replace ParentEntity and childEntities with your actual entity and field names.
Examples
Loads an Order and its Items together to avoid extra queries.
Spring Boot
SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :orderId
Fetches Customer and their Address in one query for faster access.
Spring Boot
SELECT c FROM Customer c JOIN FETCH c.address WHERE c.name = :name
Sample Program

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.

Spring Boot
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
}
OutputSuccess
Important Notes

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.

Summary

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.