반응형

[Spring JPA #23] Spring JPA EntityGraph

반응형

| EntityGraph란


  • 엔티티들은 서로 연관되어 있는 관계가 보통이며 이 관계는 그래프로 표현이 가능합니다. EntityGraph는 JPA가 어떤 엔티티를 불러올 때 이 엔티티와 관계된 엔티티를 불러올 것인지에 대한 정보를 제공합니다.
  • FetchType.LAZY 와 FetchType.EAGER로 연관 엔티티를 가져올 것인지를 결정할 수 있습니다. 하지만 이 구문은 정적이며 런타임 시 이 설정을 변경하지 못하는 단점이 있었습니다. EntityGraph는 이러한 점을 보완하고 연관 엔티티를 어떻게 로딩할 것인지에 대한 정보를 제공함으로서 엔티티 로딩 속도를 높일 수 있는 장점이 있습니다.


| EntityGraph 예제


프로젝트 구조

├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │   └── tutorial
│   │   │   └── springevent
│   │   │   ├── Application.java
│   │   │   ├── AppRunner.java
│   │   │   ├── Comment.java
│   │   │   ├── CommentRepository.java
│   │   │   ├── PostController.java
│   │   │   ├── Post.java
│   │   │   └── PostRepository.java

의존성 관리

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

소스 코드

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

@Entity
@Data
public class Post {

@Id @GeneratedValue
private Long id;

private String title;

@Temporal(TemporalType.TIMESTAMP)
private Date created;
}

@NamedEntityGraph(name = "Comment.post",
attributeNodes = @NamedAttributeNode("post"))
@Entity
@Data
public class Comment {

@Id
@GeneratedValue
private Long id;

private String comment;

@ManyToOne
private Post post;
}
  • @NamedEntityGraph 어노테이션은 재사용할 여러 엔티티 그룹을 정의할 때 사용합니다. 이 그룹을 정의하는 목적은 Repository 인터페이스 메서드에 적용되는 @EntityGraph 어노테이션이 이 엔티티 그룹에 대한 정보를 받아와 연관 엔티티 로딩 시 어떤 정책 취할 것인가를 정할 수 있는 데에 있습니다.

public interface CommentRepository extends JpaRepository<Comment, Long> {

@EntityGraph(value = "Comment.post")
Optional<Comment> getById(Long id);
}

  • 위와 같이 @NamedEntityGraph로 정의한 연관 엔티티 로딩 동작을 Repository 인터페이스의 메서드에 @EntityGraph 어노테이션을 통하여 가져옴으로서 이 어노테이션에 적용되는 로딩 정책을 해당 엔티티  그룹에 적용할 것을 명시하고 있습니다.
  • 기본적으로는 FECTH 정책을 사용하고 있으며 이것은 설정한 엔티티 속성에는 EAGER 패치 나머지는 LAZY 패치를 하는 정책입니다. 이와 반대로 LOAD 정책은 설정한 엔티티 애트리뷰트는 EAGER 패치 나머지는 기본 패치 전략을 따릅니다.


다음과 같이 속성 경로를 통해 지정할 수도 있습니다.

public interface CommentRepository extends JpaRepository<Comment, Long> {

@EntityGraph(attributePaths = {"post"})
Optional<Comment> getById(Long id);
}


https://www.inflearn.com/course/스프링-데이터-jpa


반응형

이 글을 공유하기

댓글

Designed by JB FACTORY