• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

fetch().size()

23.05.03 00:28 작성 조회수 699

0

fetchResult() 가 5.0 부터 권장하지 않는다 해서 fetch().size()를 사용한다고 하는데

 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();

        int total = queryFactory
                .selectFrom(member)
                .leftJoin(member.team, team)
                .where(
                        usernameEq(condition.getUsername()),
                        teamNameEq(condition.getTeamName()),
                        ageGoe(condition.getAgeGoe()),
                        ageLoe(condition.getAgeLoe())
                ).fetch().size();

        int size = content.size();

        return new PageImpl<>(content, pageable, total);

아래처럼 count 쿼리를 날려서 구한 total 값과

위에 content 쿼리문의 size()값이 다르게 나오던데

이 size 값은 단지 PageRequet.of로 넣어준 size 값인가요??

두 방식 중 total로 구하는 방식이 맞는건가요?

답변 1

답변을 작성해보세요.

0

OMG님의 프로필

OMG

2023.05.06

안녕하세요. 성실한 공작새님, 공식 서포터즈 OMG입니다.
.

content.size()는 조회된 데이터의 개수를 반환하며, total은 전체 데이터 건수를 반환합니다.

첫번째 쿼리를 보시면 아시겠지만

content.size()offsetlimit으로 조회된 데이터 건수를 반환하므로, total과 일치하지 않을 수 있습니다.

전체 갯수를 구하는 것이라면 후자 방식이 맞습니다.
.
감사합니다.