Spring/스프링 데이터 JPA
[스프링 데이터 JPA] 스프링 데이터 JPA 7. EntityGraph
주멘이
2021. 1. 16. 23:07
쿼리 메서드마다 연관 관계의 Fetch 모드를 설정할 수 있습니다.
경우에 따라 다른 Fetch 모드가 필요할때 사용한다.
@NamedEntityGraph
- @Entity에서 재사용할 여러 엔티티 그룹을 정의할 때 사용
- @NamedEntityGraph를 여러개 정의할 수도 있음
Comment Entity 클래스
@NamedEntityGraph(name = "Comment.post", attributeNodes = @NamedAttributeNode("post"))
@Entity
@Getter
@Setter
public class Comment {
@Id
@GeneratedValue
private Long id;
private String comment;
/*
* ManyToOne에서 fetch default = EAGER
* */
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
private Date created;
private Integer likeCount = 0;
}
@EntityGraph
- @NamedEntityGraph에 정의되어 있는 엔티티 그룹을 사용해서 실제로 동작하는 로직을 구현
- 각각의 메서드마다 다른 Fetching 전략으로 데이터를 읽어올 수 있도록 여러 가지 메서드를 만들 수 있음
// @EntityGraph(value = "Comment.post") // Entity 이름을 바로 지정해서 사용할 수도 있다
@EntityGraph(attributePaths = {"post"})
Optional<Comment> getById(Long id);