Spring Data JPA 페이징

w1nd0·2024년 5월 30일

JPA

목록 보기
18/18

QueryDSL 페이징

  1. 스프링 데이터의 Page, Pageable

Page

Page 인터페이스는 페이징된 결과 데이터를 표현한다. 이는 페이징된 데이터뿐만 아니라 페이지에 대한 메타데이터(현재 페이지, 총 페이지 수, 총 요소 수 등)를 포함한다.

  • getContent(): 현재 페이지의 데이터 리스트를 반환합니다.
  • getTotalElements(): 전체 요소 수를 반환합니다.
  • getTotalPages(): 전체 페이지 수를 반환합니다.
  • getNumber(): 현재 페이지 번호(0부터 시작)를 반환합니다.
  • getSize(): 페이지 당 요소 수를 반환합니다.
  • hasNext(): 다음 페이지가 있는지 여부를 반환합니다.
  • hasPrevious(): 이전 페이지가 있는지 여부를 반환합니다.

Pageable

Pageable 인터페이스는 페이징 정보를 캡슐화한다. 여기에는 페이지 번호, 페이지 크기, 정렬 정보가 포함된다.

  • getPageNumber(): 요청한 페이지 번호를 반환합니다.
  • getPageSize(): 페이지 당 요소 수를 반환합니다.
  • getSort(): 정렬 정보를 반환합니다.

  1. 전체 카운트를 한번에 조회하는 단순한 방법
  • fetchResult()로 한번에 조회할 수 있었으나 QueryDSL 5버전부터 fetchResult()지원을 하지 않음 fetchCount()도 지원하지 않음

  1. 데이터 내용과 전체 카운트 별도 조회 방법
  • fetchResult()를 사용하면 count쿼리가 같이 나가기 때문에 count쿼리만 따로 최적화가 불가능하다.
  • 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);
}

Count쿼리 최적화

count쿼리 생략 가능한 경우

  • 컨텐츠 사이즈가 페이지 사이즈보다 작을 경우
  • 마지막 페이지 일 경우 (offset + 컨텐츠 사이즈를 더해서 전체 사이즈 구함)
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 김영한 강사님 강의

profile
eozzeo_lago_

0개의 댓글