1. 스프링 데이터의 Page, Pageable을 활용
// List<MemberTeamDto> search(MemberSerarchCondition condition); 커스텀하게 이런 쿼리 만들 때
public interface MemberRepositoryCustom {
List<MemberTeamDto> search(MemberSerarchCondition condition);
Page<MemberTeamDto> searchPageSimple(MemberSerarchCondition condition, Pageable, pageable);
Page<MemberTeamDto> searchPageComplex(MemberSerarchCondition condition, Pageable, pageable);
}
2. 전체 카운트를 한번에 조회하는 단순한 방법
fetchReult를 통해서 컨텐츠용, 페이징용 두 개 쿼리 날림
@Override
public Page<MemberTeamDto> searchPageSimple(MemberSearchCondition condition,
Pageable pageable) {
QueryResults<MemberTeamDto> results = queryFactory
.select(new QMemberTeamDto(
member.id,
member.username,
member.age,
team.id,
team.name))
.from(member)
.leftJoin(member.team, team)
.where(usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe()))
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetchResults();
List<MemberTeamDto> content = results.getResults();
long total = results.getTotal();
return new PageImpl<>(content, pageable, total);
}
3. 데이터 내용과 전체 카운트를 별도로 조회하는 방법
이건 leftJoin이나 특정한 상황에서 content 쿼리는 복잡해도 카운트 쿼리는 단순한 경우 있을 수 있다. 이럴 때 사용
@Override
public Page<MemberTeamDto> searchPageComplex(MemberSearchCondition condition,
Pageable pageable) {
List<MemberTeamDto> content = queryFactory
.select(new QMemberTeamDto(
member.id,
member.username,
member.age,
team.id,
team.name))
.from(member)
.leftJoin(member.team, team)
.where(usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe()))
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();
long total = queryFactory
.select(member)
.from(member)
.leftJoin(member.team, team)
.where(usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe()))
.fetchCount();
return new PageImpl<>(content, pageable, total);
}
4. CountQuery 최적화
강의노트 참고
https://devlog-wjdrbs96.tistory.com/414
'Persistence Framework > ORM -JPA' 카테고리의 다른 글
JPA 양방향 순환참조 (0) | 2023.02.09 |
---|---|
JPA Insert vs. Update (0) | 2023.01.20 |
QueryDsl, 사용자 정의 Repository (0) | 2022.10.11 |
QueryDsl 설정 (0) | 2022.10.05 |
N+1문제 (0) | 2021.08.30 |