QueryDSL 페이징 처리

바로 전 포스팅인 https://yeo-computerclass.tistory.com/413에서 작성한 코드에 이어 페이징 처리를 실습해보겠습니다.

 


 

Querydsl 페이지 연동

QueryDSL Custom Repository 인터페이스에 페이지 추가

public interface MemberRepositoryCustom {
    List<MemberTeamDto> search(MemberSearchCondition condition);
    Page<MemberTeamDto> searchPage(MemberSearchCondition condition, Pageable pageable);

}

 

searchPage()

public Page<MemberTeamDto> searchPageSimple(MemberSearchCondition condition, Pageable pageable) {
    List<MemberTeamDto> content = 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();
            
    return new PageImpl<>(content, pageable, content.size());
}
  • fetchCount() / fetchResult()가 deprecated 되었습니다. 때문에 totalCount를 구하는 방법은 다음과 같이 두 가지가 있습니다.
    • 저는 일단 간단하게 fetch() 메서드로 조회한 결과에 size() 메서드 써서 totalCount를 구했습니다.
    • 두 번째 방법으로는 아래와 같이 별도의 카운트 쿼리를 날려주면 됩니다. 이때 count의 결과는 한 개이기 때문에 fetchOne() 메서드를 이용해주면 됩니다.
Long totalCount = queryFactory
		.select(member.count())
        .from(member)
        .fetchOne();

 

 

 

PageableExecutionUtils 활용

  • 스프링 데이터 라이브러리
public Page<MemberTeamDto> searchPage (MemberSearchCondition condition, Pageable pageable) {

	List<MemberTeamDto> content = 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();

	JPAQuery<Long> countQuery = queryFactory
		 .select(member.count())
		 .from(member)
		 .leftJoin(member.team, team)
		 .where(
		 		usernameEq(condition.getUsername()),
		 		teamNameEq(condition.getTeamName()),
		 		ageGoe(condition.getAgeGoe()),
				ageLoe(condition.getAgeLoe())
		 );
         
	return PageableExecutionUtils.getPage(content, pageable, countQuery::fetchOne);
}