Spring/Spring Data JPA

[Spring Data JPA] 3-2. JPA Query Methods (6)

noahkim_ 2024. 8. 2. 16:05

11. Configuring Fetch- and LoadGraphs

Entity Graph

  • 엔티티 조회 시, 연관 엔티티들을 fetch 하기 위한 구성
  • 특정 쿼리에서 어떤 연관 엔티티를 함께 로딩할 지 정의

 

종류
  • Fetch Graph: 명시된 속성 Fetch. (나머지 속성: Lazy)
  • Load Graph: 명시된 속성 Fetch. (나머지 속성: FetchType)

 

Definition

@NamedEntityGraph 
  • Entity Graph 정의 (entity)
@Entity
@NamedEntityGraph(name = "GroupInfo.detail", attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
  // 기본 페치 모드는 lazy
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  // 기타 필드 및 메서드
}

 

@NamedAttributeNode
  • entity graph 속성 정의

 

Use

@EntityGraph
  • 엔티티 그래프 참조 (repository)
  • (attribute) value: 참조할 Entity Graph
  • (attribute) type: Entity Graph Type
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);
}

 

 


출처