✅ 모임 목록 조회

Yuri Lee·2020년 11월 30일
0

N+1 Select 문제를 찾아서 해결하세요.

Event.java

    // Enrollments 중에 수락된 참가 개수를 뺀 것, 이 계산을 실행할 때 쿼리가 발생한다. 만약 모임이 5개라면 쿼리가 5번 더 발생한다. 
    public int numberOfRemainSpots() {
        return this.limitOfEnrollments - (int) this.enrollments.stream().filter(Enrollment::isAccepted).count();
    }

쿼리가 5번 발생, 이것은 big-O 에서 5N에 해당한다. 😧

이벤트를 조회할 때도 쿼리가 3번 발생한다 . 이벤트 조회, 스터디 조회, enrollment 목록 조회

4개: 스터디 조회, 이벤트 목록, 첫번째 모임의 enrollment 조회, 두번째 모임의 enrollment 조회,

Event.java

@NamedEntityGraph(
        name = "Event.withEnrollments", // 이벤트를 조회할 때 Enrollments 도 같이 읽어옴
        attributeNodes = @NamedAttributeNode("enrollments")
)
@Entity
@Getter @Setter @EqualsAndHashCode(of = "id")
public class Event {

EventRepository.java

@Transactional(readOnly = true) //Transactional 은 기본으로 readOnly 로 약속!
public interface EventRepository extends JpaRepository<Event, Long>{

    @EntityGraph(value = "Event.withEnrollments", type = EntityGraph.EntityGraphType.LOAD)
    List<Event> findByStudyOrderByStartDateTime(Study study);
}

이와 같이 설정해줌으로써 복잡도가 해결되었음!


출처 : 인프런 백기선님의 스프링과 JPA 기반 웹 애플리케이션 개발

profile
Step by step goes a long way ✨

0개의 댓글