아무거나

Entity Graph 설명 본문

Java/JPA

Entity Graph 설명

전봉근 2021. 1. 16. 19:00
반응형

Entity Graph

  • 쿼리 메서드마다 연관 관계의 fetch모드를 유연하게 설정할 수 있는 기능을 제공
  • EAGER: 끝이 One으로 끝나는 연관관계는 기본값이 EAGER 모드이다.
    • 참조하고 있는 다른 Entity의 값도 가져온다.
  • LAZY: 끝이 Many로 끝나는 연관관계는 기본값이 LAZY 모드이다.
    • 자기 자신만 가져온 후 참조하고 있는 다른 Entity에 접근하면 그때야 다시 쿼리 실행
  • 예제코드
    • 기본은 EAGER지만 LAZY로 정보를 가져올 때
        @Entity
        public class Reply {
          @Id
          @GeneratedValue
          private Long id;
          
          private String reply;
      
          /**
            @ManyToOne 은 참조하고 있는 다른 Entity의 값도 가져온다(Reply를 조회하였지만 자동으로 Board 값도 가져옴)
            @ManyToOne(fetch = FetchType.LAZY) 은 자기 자신만 가져온 후 참조하고 있는 다른 Entity에 접근하면 그때야 다시 쿼리 실행(Reply 조회시 해당 Reply 정보들만 가져옴)  
          */
          @ManyToOne(fetch = FetchType.LAZY)
          // @ManyToOne
          private Board board;
        }
      
        @Entity
        public class Board {
          @Id
          @GeneratedValue
          private Long id;
      
          private String title;
          private LocalDateTime created;
        }
      
    • 기본은 LAZY지만 EAGER로 정보를 가져올 때 (@NamedEntityGraph 활용)
        // name: 해당 그래프 이름, @NamedAttributeNode: 연관 관계 이름
        @NamedEntityGraph(name = "Reply.board", attributeNodes = @NamedAttributeNode("board"))
        @Entity
        public class Reply {
          @Id
          @GeneratedValue
          private Long id;
          
          private String reply;
      
          @ManyToOne(fetch = FetchType.LAZY)
          private Board board;
        }
      
        @Entity
        public class Board {
          @Id
          @GeneratedValue
          private Long id;
      
          private String title;
          private LocalDateTime created;
        }
      
        public interface ReplyRepository extends JpaRepository<Reply, Long> {
            @EntityGraph(value = "Reply.board")
            Optional<Reply> getById(Long id);
        }
      
  •  
반응형
Comments