[Spring Data JPA] OneToMany fetch후 페이징할 때

서규범·2023년 8월 22일
0

1.

@EntityGraph(attributePaths = {"responseEntitySet","responseEntitySet.questionOptionEntity","fileEntitySet"})
Page<UserEntity> findAllByRole(Pageable pageable, UserRole role);

-->

  • spring.jpa.show-sql=true

  • spring.jpa.properties.hibernate.format_sql=true

시 조회 가능

  • 쿼리가 excute될 때, 요청한 페이지만큼 조회하는 것이 아닌 전체조회가 발생됨.
  • 전체조회 결과를 in-memory에 두고 나중에 paging처리를 해서 반환하기때문에 페이징된 결과를 받아볼 수 있음.

2.

@EntityGraph 어노테이션 제거

Page<UserEntity> findAllByRole(Pageable pageable, UserRole role);

-> limit 절이 적용되었지만,

  • response, file: 조회된 user의 수만큼 n+1 발생
  • question_option: response의 수만큼 n+1 발생

3.

@BatchSize 어노테이션 적용

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="user_id")
@BatchSize(size=100)
private Set<ResponseEntity> responseEntitySet = new LinkedHashSet<>();

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="user_id")
@BatchSize(size=100)
private Set<FileEntity> fileEntitySet = new LinkedHashSet<>();
  • @EntityGraph를 이용한 페이징
    page 값과 상관 없이 전체결과를 조회한 후, 나중에 페이징 처리
  • @EntityGraph 없이 페이징
    limit을 이용해 페이지만큼 조회하지만, n+1이 발생
  • @EntityGraph 없이 페이징 + default_batch_fetch_size 혹은 @BatchSize 설정
    limit을 이용해 조회하고, n+1 없이 in 절을 활용해 조회
profile
하려 하자

0개의 댓글