Post

[QueryDSL #2] 프로젝션·동적 쿼리·페이징, QueryDSL 실무 활용 정리

[QueryDSL #2] 프로젝션·동적 쿼리·페이징, QueryDSL 실무 활용 정리

1편에 이어 QueryDSL을 실무에서 쓸 때 필요한 내용을 정리했습니다. 프로젝션으로 DTO를 조회하는 방법, BooleanBuilder와 where 다중 파라미터를 이용한 동적 쿼리, 벌크 연산, 그리고 Spring Data JPA와 함께 쓰는 페이징 최적화를 다룹니다.

주요 키워드

  • 프로젝션, Tuple, DTO 조회
  • Projections.bean / fields / constructor, @QueryProjection
  • 동적 쿼리: BooleanBuilder, where 다중 파라미터, BooleanExpression
  • 벌크 연산(수정·삭제)과 영속성 컨텍스트
  • SQL function 호출
  • 페이징 최적화: count 쿼리 분리, PageableExecutionUtils
  • QuerydslPredicateExecutor, QuerydslRepositorySupport

프로젝션

프로젝션은 select 대상을 지정하는 것입니다.

  • 대상이 하나면 타입을 명확하게 지정할 수 있습니다 (예: List<String>)
  • 대상이 둘 이상이면 기본적으로 Tuple로 반환됩니다
  • DTO로 바로 조회할 수도 있습니다

Tuple은 QueryDSL 타입이라 리포지토리 밖(서비스, 컨트롤러)까지 넘기면 그 계층들이 QueryDSL에 의존하게 됩니다. 리포지토리 안에서만 쓰고, 밖으로는 DTO로 바꿔 내보내는 게 좋습니다.

DTO로 조회하는 세 가지 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 1. 프로퍼티 접근 (setter 사용, 기본 생성자 필요)
queryFactory
        .select(Projections.bean(MemberDto.class, member.username, member.age))
        .from(member)
        .fetch();

// 2. 필드 직접 접근 (getter/setter 없어도 됨)
queryFactory
        .select(Projections.fields(MemberDto.class, member.username, member.age))
        .from(member)
        .fetch();

// 3. 생성자 사용 (생성자 파라미터 타입·순서가 맞아야 함)
queryFactory
        .select(Projections.constructor(MemberDto.class, member.username, member.age))
        .from(member)
        .fetch();

bean과 fields는 이름으로 값을 매칭합니다. 그래서 DTO의 필드명과 엔티티의 필드명이 다르면 값이 null로 들어갑니다. 이때는 .as()로 이름을 맞춰 줍니다.

1
2
3
4
5
6
7
8
9
10
queryFactory
        .select(Projections.fields(UserDto.class,
                member.username.as("name"),
                ExpressionUtils.as(
                        JPAExpressions
                                .select(memberSub.age.max())
                                .from(memberSub), "age")
        ))
        .from(member)
        .fetch();

서브쿼리처럼 .as()를 바로 붙일 수 없는 표현식에는 ExpressionUtils.as(표현식, 별칭)을 씁니다.

@QueryProjection

DTO의 생성자에 @QueryProjection을 붙이고 빌드하면 DTO용 Q클래스(QMemberDto)가 생성됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
@Data
@NoArgsConstructor
public class MemberDto {
    private String username;
    private int age;

    @QueryProjection
    public MemberDto(String username, int age) {
        this.username = username;
        this.age = age;
    }
}
1
2
3
4
queryFactory
        .select(new QMemberDto(member.username, member.age))
        .from(member)
        .fetch();
장점단점
생성자를 그대로 호출하므로 타입·개수 오류를 컴파일 시점에 잡을 수 있음DTO용 Q클래스를 생성해야 함
 DTO가 QueryDSL에 의존하게 됨. DTO는 서비스·컨트롤러 등 여러 계층에서 쓰이므로, 아키텍처 관점에서 허용할지 판단이 필요함

Projections.constructor도 생성자를 쓰지만 타입이나 개수가 틀리면 런타임에야 오류가 납니다. 이게 @QueryProjection과의 가장 큰 차이입니다.


동적 쿼리

검색 조건이 있을 때도 있고 없을 때도 있는 쿼리를 작성하는 방법은 두 가지입니다.

1. BooleanBuilder

조건이 null이 아닐 때만 builder에 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private List<Member> searchMember1(String usernameCond, Integer ageCond) {
    BooleanBuilder builder = new BooleanBuilder();
    if (usernameCond != null) {
        builder.and(member.username.eq(usernameCond));
    }
    if (ageCond != null) {
        builder.and(member.age.eq(ageCond));
    }

    return queryFactory
            .selectFrom(member)
            .where(builder)
            .fetch();
}

2. where 다중 파라미터

where()에 null이 들어가면 무시된다는 점을 이용합니다. 조건이 있으면 BooleanExpression을, 없으면 null을 반환하는 메서드를 만들어 where 절에 나열합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private List<Member> searchMember2(String usernameCond, Integer ageCond) {
    return queryFactory
            .selectFrom(member)
            .where(usernameEq(usernameCond), ageEq(ageCond))
            .fetch();
}

private BooleanExpression usernameEq(String usernameCond) {
    return usernameCond != null ? member.username.eq(usernameCond) : null;
}

private BooleanExpression ageEq(Integer ageCond) {
    return ageCond != null ? member.age.eq(ageCond) : null;
}

BooleanBuilder보다 훨씬 깔끔하고, 쿼리 본문만 읽어도 어떤 조건으로 조회하는지 바로 보입니다. 조건 메서드는 다른 쿼리에서 재사용할 수 있고, 여러 조건을 묶어 하나로 조립할 수도 있습니다.

1
2
3
4
5
private BooleanBuilder allEq(String usernameCond, Integer ageCond) {
    return new BooleanBuilder()
            .and(usernameEq(usernameCond))
            .and(ageEq(ageCond));
}

조립할 때는 null에 주의해야 합니다. usernameEq(usernameCond).and(ageEq(ageCond))처럼 쓰면 usernameEq가 null을 반환할 때 NullPointerException이 납니다. 위처럼 BooleanBuilder로 감싸면 and(null)은 무시되므로 안전합니다.

검색 조건 DTO를 만들 때 팁

  • 필드는 기본 타입(int)보다 래퍼 클래스(Integer)를 씁니다. 조건이 없는 null과 값이 0인 경우를 구분하기 위해서입니다
  • 문자열은 화면에서 null이 아니라 빈 문자열("")로 넘어오는 경우가 많습니다. 스프링의 StringUtils.hasText()로 검사하면 둘 다 걸러 낼 수 있습니다
  • 검색 조건이 하나도 없으면 전체 데이터를 조회하는 쿼리가 나갑니다. 페이징을 걸거나 최소한의 기본 조건을 둬서 이를 막는 게 좋습니다
1
2
3
private BooleanExpression usernameEq(String username) {
    return hasText(username) ? member.username.eq(username) : null;
}

수정·삭제 벌크 연산

쿼리 한 번으로 대량의 데이터를 수정하거나 삭제합니다. 실행 결과로 영향받은 row 수를 반환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 수정
long count = queryFactory
        .update(member)
        .set(member.username, "비회원")
        .where(member.age.lt(28))
        .execute();

// 기존 값에 연산 (곱하기는 multiply())
queryFactory
        .update(member)
        .set(member.age, member.age.add(1))
        .execute();

// 삭제
queryFactory
        .delete(member)
        .where(member.age.gt(18))
        .execute();

벌크 연산은 영속성 컨텍스트를 거치지 않고 DB에 바로 쿼리를 보냅니다. 그래서 영속성 컨텍스트에는 변경 전 데이터가 그대로 남아 DB와 달라집니다. 벌크 연산 뒤에는 반드시 em.flush(), em.clear()로 영속성 컨텍스트를 초기화해야 합니다.


SQL function 호출

Expressions.stringTemplate()으로 SQL 함수를 호출할 수 있습니다. replace, lower 같은 DB 기본 함수는 바로 쓸 수 있고, 사용자 정의 함수는 Dialect에 등록한 뒤 쓸 수 있습니다. 등록 방법은 Hibernate 버전에 따라 다릅니다.

1
2
3
4
5
6
queryFactory
        .select(Expressions.stringTemplate(
                "function('replace', {0}, {1}, {2})",
                member.username, "member", "M"))
        .from(member)
        .fetch();

Spring Data JPA와 함께 쓰기

사용자 정의 리포지토리

Spring Data JPA 리포지토리는 인터페이스라서 QueryDSL 코드를 직접 넣을 수 없습니다. 사용자 정의 인터페이스를 만들고 JPAQueryFactory로 구현한 뒤, 기존 리포지토리가 그 인터페이스를 함께 상속하게 합니다. 구현 클래스 이름은 리포지토리 인터페이스 이름 + Impl로 지어야 Spring Data JPA가 인식합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public interface MemberRepositoryCustom {
    List<MemberTeamDto> search(MemberSearchCondition condition);
}

public class MemberRepositoryImpl implements MemberRepositoryCustom {
    private final JPAQueryFactory queryFactory;

    public MemberRepositoryImpl(EntityManager em) {
        this.queryFactory = new JPAQueryFactory(em);
    }

    @Override
    public List<MemberTeamDto> search(MemberSearchCondition condition) {
        // QueryDSL 쿼리 작성
    }
}

public interface MemberRepository
        extends JpaRepository<Member, Long>, MemberRepositoryCustom {
}

페이징 최적화

fetchResults()는 deprecated이고 쓰지 않는 게 좋습니다. 내부적으로 조회 쿼리에 count만 붙여 실행하기 때문에, 개수만 세면 되는 상황에도 불필요한 조인이 함께 실행돼 성능이 떨어집니다. 같은 이유로 fetchCount()도 deprecated입니다.

그래서 조회 쿼리와 count 쿼리를 따로 작성합니다. count는 select 절에 count()를 쓰고 fetchOne()으로 가져옵니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public Page<MemberTeamDto> searchPage(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()))
            .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()));

    return PageableExecutionUtils.getPage(content, pageable, countQuery::fetchOne);
}

PageableExecutionUtils.getPage()는 count 쿼리가 필요 없을 때 실행하지 않습니다. count 쿼리를 바로 실행하지 않고 함수(countQuery::fetchOne)로 넘기는 이유입니다.

  • 첫 페이지인데 조회된 데이터가 페이지 크기보다 적을 때
  • 마지막 페이지일 때 (offset + 조회된 데이터 수로 전체 개수를 알 수 있음)

예를 들어 전체 데이터가 100개인데 size를 200으로 조회하면, 조회 쿼리에서 이미 전부 가져왔으므로 count 쿼리를 보내지 않습니다.

그 외 Spring Data JPA가 제공하는 QueryDSL 기능

기능내용한계
QuerydslPredicateExecutor리포지토리가 상속하면 findAll() 등에 where 조건(Predicate)을 바로 넘길 수 있음left join 불가. 서비스 계층이 QueryDSL에 의존하게 됨
Web 지원 (@QuerydslPredicate)요청 파라미터를 Predicate로 바로 바인딩조건을 세밀하게 커스터마이징하기 어렵고, 컨트롤러가 QueryDSL에 의존하게 됨
QuerydslRepositorySupport상속하면 EntityManager 주입 없이 from()부터 쿼리를 작성할 수 있고, getQuerydsl().applyPagination()으로 페이징 적용QueryDSL 3 시절에 만들어져 JPAQueryFactory를 지원하지 않음. from()으로 시작해 가독성이 떨어지고 Sort 지원도 불안정함

복잡한 환경일수록 이런 기능은 한계가 있어서, 보통은 앞에서 본 사용자 정의 리포지토리 + JPAQueryFactory 조합을 씁니다. QuerydslRepositorySupport의 단점을 보완한 지원 클래스를 직접 만들어 쓰는 방법도 있습니다.


덧붙임: 프로필별 더미 데이터 넣기

API를 개발하면서 로컬에서만 샘플 데이터를 넣고 싶을 때 쓴 방법입니다.

  • src/main/resources와 src/test/resources에 각각 application.yml을 두고 프로필을 다르게 지정하면, 로컬과 테스트 환경을 분리할 수 있습니다
  • 특정 프로필에서만 등록할 컴포넌트에는 @Profile("local")을 붙입니다
  • 더미 데이터 생성 클래스에 @Profile("local")을 붙이고, 데이터 생성 로직을 @PostConstruct에서 실행합니다

@PostConstruct 메서드에는 @Transactional이 적용되지 않습니다. 초기화 시점에는 트랜잭션 프록시가 아직 준비되지 않았기 때문입니다. 그래서 트랜잭션이 필요한 데이터 생성 로직은 별도의 빈으로 분리하고, @PostConstruct에서는 그 빈을 호출만 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Profile("local")
@Component
@RequiredArgsConstructor
public class InitMember {
    private final InitMemberService initMemberService;

    @PostConstruct
    public void init() {
        initMemberService.init();
    }

    @Component
    static class InitMemberService {
        @PersistenceContext
        EntityManager em;

        @Transactional
        public void init() {
            // 더미 데이터 저장
        }
    }
}
This post is licensed under CC BY 4.0 by the author.