[Spring] 7. N+1

Kim yoon beom·2025년 5월 14일
1


해당 repository 코드

public interface CommentRepository extends JpaRepository<Comment, Long> {

    @Query("SELECT c FROM Comment c JOIN c.user WHERE c.todo.id = :todoId")
    List<Comment> findByTodoIdWithUser(@Param("todoId") Long todoId);
}

N+1 문제를 해결하는 건 여러가지 방법이 있지만 Fetch Join으로 해결하였다.

join 옆에 fetch를 붙여주자.


해결 후 repository 코드

public interface CommentRepository extends JpaRepository<Comment, Long> {

    @Query("SELECT c FROM Comment c JOIN FETCH c.user WHERE c.todo.id = :todoId")
    List<Comment> findByTodoIdWithUser(@Param("todoId") Long todoId);
}
profile
나는.원한다.개발자

1개의 댓글

comment-user-thumbnail
2025년 5월 15일

N + 1 문제 해결방법중에 Fetch Join을 선택하시다니 대단하십니다

답글 달기