• 먼저 생각해 볼 수 있는 방법은 @EntityGraph로 한 번에 다 가져올 수 있습니다.
  • join fetch을 사용하여 한 번에 쿼리할 수 있습니다.
  • hibernate의 default fetch를 사용하는 방법이 있습니다.

앞서 살펴본 EntityGraph에 이어 join fetch을 살펴 보겠습니다.

2. Join Fetch를 사용하는 방법

먼저 살펴본 방법(2020/06/11 - [Programming/JPA] - N + 1 문제 해결 1)은 JpaRepository에서 원하는 쿼리로 바뀌도록 @EntityGraph를 이용하여 가이드 했다면 이번 방법은 JPQL을 사용하여 직접적으로 해결하는 방법입니다.

public interface PostRepository extends JpaRepository<Post, Long> {

    @Query("select p from Post p join fetch p.comments")
    List<Post> findAllWithComments();

}

해결편1에서 사용한 소스에 PostRepository만 바뀌었습니다. "join fetch p.comments"부분이 추가 되었습니다.

@SpringBootTest
class PostRepositoryTest {

    @Autowired
    private PostService postService;
    @Autowired
    private PostRepository postRepository;

    @BeforeEach
    public void setup() {
        Post post = new Post();
        post.setTitle("첫 포스트");

        Comment comment1 = new Comment();
        comment1.setComment("첫 댓글~! ");
        comment1.setPost(post);
        post.getComments().add(comment1);

        Comment comment2 = new Comment();
        comment2.setComment("두번째야~");
        post.getComments().add(comment2);
        comment2.setPost(post);

        Post post2 = new Post();
        post2.setTitle("내가 2등~");

        Comment comment3 = new Comment();
        comment3.setComment("좋아요~");
        comment3.setPost(post2);
        post2.getComments().add(comment3);

        Comment comment4 = new Comment();
        comment4.setComment("감사합니다.");
        comment4.setPost(post2);
        post2.getComments().add(comment4);

        Comment comment5 = new Comment();
        comment5.setComment("다음글 기대할께요.");
        comment5.setPost(post2);
        post2.getComments().add(comment5);

        postRepository.save(post);
        postRepository.save(post2);
    }

    @Test
    void testNPlusOne() {
        // lazy loading
        System.out.println("===== LAZY");
        System.out.println("LAZY : " + postService.findAllComments());

        // Join fetch
        System.out.println("===== JoinFetch");
        System.out.println("JoinFetch : " + postService.findAllWithComments());
    }
}

결과는 아래와 같이 inner join으로 실행되었죠...

===== JoinFetch
Hibernate: 
    select
        post0_.id as id1_3_0_,
        comments1_.id as id1_2_1_,
        post0_.title as title2_3_0_,
        comments1_.comment as comment2_2_1_,
        comments1_.post_id as post_id3_2_1_,
        comments1_.post_id as post_id3_2_0__,
        comments1_.id as id1_2_0__ 
    from
        post post0_ 
    inner join
        comment comments1_ 
            on post0_.id=comments1_.post_id
2020-06-11 17:58:26.842 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_3_0_] : [BIGINT]) - [1]
2020-06-11 17:58:26.843 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [2]
2020-06-11 17:58:26.843 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([title2_3_0_] : [VARCHAR]) - [첫 포스트]
2020-06-11 17:58:26.844 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([comment2_2_1_] : [VARCHAR]) - [첫 댓글~! ]
2020-06-11 17:58:26.844 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_1_] : [BIGINT]) - [1]
2020-06-11 17:58:26.844 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_0__] : [BIGINT]) - [1]
2020-06-11 17:58:26.845 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_0__] : [BIGINT]) - [2]
2020-06-11 17:58:26.845 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_3_0_] : [BIGINT]) - [1]
2020-06-11 17:58:26.846 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [3]
2020-06-11 17:58:26.846 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([comment2_2_1_] : [VARCHAR]) - [두번째야~]
2020-06-11 17:58:26.846 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_1_] : [BIGINT]) - [1]
2020-06-11 17:58:26.847 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_0__] : [BIGINT]) - [1]
2020-06-11 17:58:26.849 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_0__] : [BIGINT]) - [3]
2020-06-11 17:58:26.850 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_3_0_] : [BIGINT]) - [4]
2020-06-11 17:58:26.850 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [5]
2020-06-11 17:58:26.854 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([title2_3_0_] : [VARCHAR]) - [내가 2등~]
2020-06-11 17:58:26.855 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([comment2_2_1_] : [VARCHAR]) - [좋아요~]
2020-06-11 17:58:26.855 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_1_] : [BIGINT]) - [4]
2020-06-11 17:58:26.857 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_0__] : [BIGINT]) - [4]
2020-06-11 17:58:26.857 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_0__] : [BIGINT]) - [5]
2020-06-11 17:58:26.857 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_3_0_] : [BIGINT]) - [4]
2020-06-11 17:58:26.857 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [6]
2020-06-11 17:58:26.858 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([comment2_2_1_] : [VARCHAR]) - [감사합니다.]
2020-06-11 17:58:26.858 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_1_] : [BIGINT]) - [4]
2020-06-11 17:58:26.859 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_0__] : [BIGINT]) - [4]
2020-06-11 17:58:26.859 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_0__] : [BIGINT]) - [6]
2020-06-11 17:58:26.861 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_3_0_] : [BIGINT]) - [4]
2020-06-11 17:58:26.862 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [7]
2020-06-11 17:58:26.863 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([comment2_2_1_] : [VARCHAR]) - [다음글 기대할께요.]
2020-06-11 17:58:26.863 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_1_] : [BIGINT]) - [4]
2020-06-11 17:58:26.863 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([post_id3_2_0__] : [BIGINT]) - [4]
2020-06-11 17:58:26.864 TRACE 3302 --- [    Test worker] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_0__] : [BIGINT]) - [7]
JoinFetch : [[Comment(id=2, comment=첫 댓글~! ), Comment(id=3, comment=두번째야~)], [Comment(id=2, comment=첫 댓글~! ), Comment(id=3, comment=두번째야~)], [Comment(id=5, comment=좋아요~), Comment(id=6, comment=감사합니다.), Comment(id=7, comment=다음글 기대할께요.)], [Comment(id=5, comment=좋아요~), Comment(id=6, comment=감사합니다.), Comment(id=7, comment=다음글 기대할께요.)], [Comment(id=5, comment=좋아요~), Comment(id=6, comment=감사합니다.), Comment(id=7, comment=다음글 기대할께요.)]]

@EntityGraph를 사용한 1편에서는 left outer join으로 실행 되었던 것을 기억하시나요?

그렇습니다. 이 두 방법은 실행 방식이 다릅니다.

  • @EntityGraph : left outer join
  • join fetch : inner join

그런데 두 방법 모두 comments가 중복되어서 출력될 수 있습니다. 카테시안 곱이 되기 때문입니다.

Cartesian Product 해결

코너속의 코너

먼저 두 가지 방법이 있습니다.

  1. collection을 List가 아닌 Set으로 바꾸는 방법입니다.
    private Set<Comment> comments = new LinkedHashSet<>();
    (참고로 HashSet으로 하면 중복 제거는 되는데 순서가 보장이 안됩니다.)
  2. @Query에서 distinct를 사용하는 방법입니다.
    @Query("select distinct p from Post p join fetch p.comments")
    List<Post> findAllWithComments();

개인적으로는 List를 사용하는 것이 더 좋아 보입니다. 왜냐하면 JpaRepository의 interface들은 다 List이기 때문입니다. 하지만 상황에 따라 Set을 쓰지 않는다는 보장은 없으니 여러모로 알고 있는 것이 이로워 보입니다. 그리고 항상 느끼는 것이지만 발생된 query와 결과는 꼭 확인이 필요합니다.

 

github source : https://github.com/aloftcat/blog-code/tree/master/jpa/NPlusOne

'Programming > JPA' 카테고리의 다른 글

N + 1 문제 해결 3  (0) 2020.06.15
N + 1 문제 해결 1  (0) 2020.06.11
N + 1 문제 원인  (0) 2020.06.05
왜 JPA를 써야할까?  (0) 2020.06.05
JPA 기본 Annotation 정리  (7) 2019.07.04

+ Recent posts