
📘 N+1 문제와 해결방법 알아보기
Entity
//getter, setter 생략
@Entity
public class Post {
@Id @GeneratedValue
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY) // 지연로딩이 핵심
private User author;
}
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
}
문제 발생 코드
public void showPosts() {
List<Post> posts = postRepository.findAll(); // 1번 쿼리
for (Post post : posts) {
// N번 쿼리
System.out.println(post.getTitle() + " - " + post.getAuthor().getName());
}
}
findAll() 로 게시글을 가져온다. (1번)getAuthor().getName() 실행 때마다 작성자 정보가 DB 에서 따로 조회된다. (N번)Fetch Join
@Query("SELECT p FROM Post p JOIN FETCH p.author")
List<Post> findAllWithAuthor();
Join Fetch 를 직접 작성한다.EntityGraph
@EntityGraph(attributePaths = "author")
List<Post> findAll();
Fetch Join 하게 만든다.