[java] Java Querydsl을 사용하여 동적 쿼리 작성하기

지금까지 정적 쿼리를 작성하는 방법을 살펴보았는데, 이제는 동적 쿼리를 작성하는 방법에 대해 알아보겠습니다. 동적 쿼리는 실행 시점에 조건이나 정렬 등을 변경할 수 있는 쿼리입니다.

Querydsl 동적 쿼리 설정

Querydsl을 사용한 동적 쿼리 작성을 위해 먼저 관련 의존성을 추가해야 합니다. pom.xml 파일에 다음 의존성을 추가합니다.

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-core</artifactId>
    <version>{querydsl-version}</version>
</dependency>
<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
    <version>{querydsl-version}</version>
</dependency>

다음으로, Querydsl로 작성한 쿼리 클래스를 사용하기 위해 Maven build 설정에서 Q클래스 생성을 추가합니다.

<plugins>
    <plugin>
        <groupId>com.mysema.maven</groupId>
        <artifactId>apt-maven-plugin</artifactId>
        <version>{apt-plugin-version}</version>
        <executions>
            <execution>
                <goals>
                    <goal>process</goal>
                </goals>
                <configuration>
                    <outputDirectory>target/generated-sources/java</outputDirectory>
                    <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>

이제 Querydsl을 사용하여 동적 쿼리를 작성해보겠습니다.

동적 쿼리 작성 예제

다음은 동적 쿼리를 작성하는 예제입니다. 예를 들어, 사용자가 검색 조건을 선택하고 동적으로 해당 조건에 맞는 검색 결과를 가져오는 기능을 구현한다고 가정해봅시다.

public List<User> searchUsers(String name, Integer age, String city) {
    JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);
    QUser user = QUser.user;

    BooleanBuilder builder = new BooleanBuilder();

    if (name != null && !name.isEmpty()) {
        builder.and(user.name.contains(name));
    }

    if (age != null) {
        builder.and(user.age.eq(age));
    }

    if (city != null && !city.isEmpty()) {
        builder.and(user.city.eq(city));
    }

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

위의 예제에서는 사용자가 선택한 조건에 따라 조건절을 추가하는 방식으로 동적 쿼리를 작성하였습니다. BooleanBuilder 클래스를 사용하여 동적으로 조건을 추가하며, selectFrom 메서드를 사용하여 쿼리를 작성합니다.

결론

위의 예제를 통해 Java Querydsl을 사용하여 동적 쿼리를 작성하는 방법을 확인할 수 있었습니다. 동적 쿼리를 작성하면 실행 시점에 조건을 변경할 수 있어 더 유연한 쿼리 작성이 가능해집니다. Querydsl을 사용하면 편리하게 동적 쿼리를 작성할 수 있으며, 코드의 가독성과 유지보수성을 높일 수 있습니다.

참고 자료