Spring JPA - @EntityGraph

By default, Spring Data JPA loads related data lazily, which can cause the N+1 problem — one query for the main data and more for each related item. @EntityGraph annotation fixes this by letting you load related data in a single query, without changing your entity mapping. It’s simple, improves performance, and avoids writing custom JOIN FETCH queries. Example Let’s say you have a Post entity that references an Author. Entities @Entity public class Post { @Id private Long id; private String title; @ManyToOne(fetch = FetchType.LAZY) private Author author; } @Entity public class Author { @Id private Long id; private String name; } Repository public interface PostRepository extends JpaRepository { // attributePaths specifies related entities to eagerly load @EntityGraph(attributePaths = {"author"}) List findAll(); } Now, if you create a simple controller to return all posts and have SQL logging enabled, you'll see the queries printed in the console. With @EntityGraph, only one query runs to fetch both the post and its author. Without it, multiple queries are executed — one for the posts and one for each author — which is the N+1 problem. ✅ Using @EntityGraph Only one query — fast and efficient. select p.id, p.title, a.id, a.name from post p left join author a on p.author_id = a.id

May 2, 2025 - 02:42
 0
Spring JPA - @EntityGraph

By default, Spring Data JPA loads related data lazily, which can cause the N+1 problem — one query for the main data and more for each related item. @EntityGraph annotation fixes this by letting you load related data in a single query, without changing your entity mapping. It’s simple, improves performance, and avoids writing custom JOIN FETCH queries.

Example

Let’s say you have a Post entity that references an Author.

Entities

@Entity
public class Post {
    @Id
    private Long id;
    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    private Author author;
}

@Entity
public class Author {
    @Id
    private Long id;
    private String name;
}

Repository

public interface PostRepository extends JpaRepository {

    // attributePaths specifies related entities to eagerly load
    @EntityGraph(attributePaths = {"author"})
    List findAll();
}

Now, if you create a simple controller to return all posts and have SQL logging enabled, you'll see the queries printed in the console.

With @EntityGraph, only one query runs to fetch both the post and its author. Without it, multiple queries are executed — one for the posts and one for each author — which is the N+1 problem.

✅ Using @EntityGraph
Only one query — fast and efficient.

select p.id, p.title, a.id, a.name
from post p
left join author a on p.author_id = a.id