본문 바로가기
Tech/JPA

[JPA] @EntityGraph 사용

by 싱브이 2024. 4. 16.
728x90
반응형

하위 엔티티를 로딩할 때 가장 간단한 방법은 eager(즉시) 로딩을 사용하는 것이지만, @OneToMany를 비롯하여 가능한한 lazy(지연) 로딩을 이용하는 것이 기본적이다. 

지연 로딩이지만, 한번에 조인 처리로 select이 이루어지도록 하는 방법이 있다.

 

 


@EntityGraph

@EntityGraph란, JPA에서 fetch 조인을 어노테이선을 통해 사용할 수 있도록 하는 기능이다. 

 

연관관계가 있는 엔티티를 조회할 경우 지연로딩으로 설정되어 있는 경우의 연관관계에서 종속된 엔티티는 쿼리 실행 시 select이 되지 않고 proxy 객체를 만들어 엔티티가 적용시킨 후 해당 proxy 객체를 호출할 때마다 select 쿼리가 실행된다. 

 

- attributePaths 속성을 이용해서 같이 로딩해야 하는 속성을 명시할 수 있다.

 

 

 


내가 적용한

public interface BoardRepository extends JpaRepository<Board, Long>, BoardSearch {

    @EntityGraph(attributePaths = {"imageSet"})
    @Query("select b from Board b where b.bno =:bno")
    Optional<Board> findByIdWithImage(@Param("bno") Long bno);
}

 

Test

    @Test
    void testReadWithImages(){
        Optional<Board> result = boardRepository.findByIdWithImage(1L);
        Board board = result.orElseThrow();
        log.info(board);
        log.info("--------------------");
        for (BoardImage boardImage : board.getImageSet()) {
            log.info(boardImage);

        }
    }

 

 

결과

 

 

 

 

 

728x90
반응형

댓글