Page 인터페이스는 페이징된 결과 데이터를 표현한다. 이는 페이징된 데이터뿐만 아니라 페이지에 대한 메타데이터(현재 페이지, 총 페이지 수, 총 요소 수 등)를 포함한다.
getContent(): 현재 페이지의 데이터 리스트를 반환합니다.getTotalElements(): 전체 요소 수를 반환합니다.getTotalPages(): 전체 페이지 수를 반환합니다.getNumber(): 현재 페이지 번호(0부터 시작)를 반환합니다.getSize(): 페이지 당 요소 수를 반환합니다.hasNext(): 다음 페이지가 있는지 여부를 반환합니다.hasPrevious(): 이전 페이지가 있는지 여부를 반환합니다.Pageable 인터페이스는 페이징 정보를 캡슐화한다. 여기에는 페이지 번호, 페이지 크기, 정렬 정보가 포함된다.
getPageNumber(): 요청한 페이지 번호를 반환합니다.getPageSize(): 페이지 당 요소 수를 반환합니다.getSort(): 정렬 정보를 반환합니다.fetchResult()로 한번에 조회할 수 있었으나 QueryDSL 5버전부터 fetchResult()지원을 하지 않음 fetchCount()도 지원하지 않음fetchResult()를 사용하면 count쿼리가 같이 나가기 때문에 count쿼리만 따로 최적화가 불가능하다. public Page<MemberTeamDto> searchPage(MemberSearchCondition condition, Pageable pageable) {
List<MemberTeamDto> results = queryFactory
.select(new QMemberTeamDto(
member.id.as("memberId"),
member.username,
member.age,
team.id.as("teamId"),
team.name.as("teamName")
))
.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.id.count())
.from(member)
.leftJoin(member.team, team)
.where(
usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe())
)
.fetchOne();
return new PageImpl<>(results, pageable, total);
}
JPAQuery<Long> countQuery = queryFactory //전체 카운트
.select(member.id.count())
.from(member)
.leftJoin(member.team, team)
.where(
usernameEq(condition.getUsername()),
teamNameEq(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe())
);
return PageableExecutionUtils
.getPage(results, pageable, countQuery::fetchOne);
PageableExecutionUtils의 내부에서 조건을 확인하고count쿼리가 필요할 경우에만 countQuery::fetchOne를 호출하여query문을 작성한다.
출처 / 참고: Iflearn 김영한 강사님 강의