[java] Querydsl을 사용하여 복잡한 쿼리 작성하기

Querydsl은 자바 기반의 오픈소스 라이브러리로, SQL과 NoSQL 데이터베이스에 접근하여 쿼리를 작성하는 데 사용됩니다. 이를 통해 복잡한 쿼리를 보다 쉽고 간결하게 작성할 수 있습니다. 이번 글에서는 Querydsl을 사용하여 복잡한 쿼리를 작성하는 방법에 대해 알아보겠습니다.

1. Querydsl 설정

우선 Querydsl을 사용하기 위해 프로젝트에 Querydsl 라이브러리를 추가해야 합니다. Gradle을 사용하는 경우, build.gradle 파일에 다음 의존성을 추가합니다.

dependencies {
    implementation 'com.querydsl:querydsl-core:4.4.0'
    implementation 'com.querydsl:querydsl-jpa:4.4.0'
}

Maven을 사용하는 경우, pom.xml 파일에 다음 의존성을 추가합니다.

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

2. Entity 클래스 작성하기

Querydsl을 사용하기 위해서는 Entity 클래스를 작성해야 합니다. 이 예제에서는 간단한 예로 User 엔티티 클래스를 작성하도록 하겠습니다.

@Entity
public class User {
    @Id
    private Long id;
    
    private String name;
    private int age;
    
    // getters and setters
}

3. Querydsl 쿼리 작성하기

Querydsl을 사용하여 쿼리를 작성하려면 QEntity 클래스를 생성해야 합니다. 이 클래스는 Querydsl에서 사용할 수 있도록 엔티티 클래스를 확장하는 역할을 합니다. Querydsl의 Q 클래스를 생성하는 방법에는 여러 가지가 있지만, 가장 일반적인 방법은 Querydsl Maven Plugin을 사용하는 것입니다. 해당 플러그인을 사용하지 않는 경우, Q 클래스를 수동으로 생성해야 합니다.

./gradlew compileQuerydsl

위 명령어를 실행하면 target/generated-sources/java 디렉토리에 Q 클래스가 생성됩니다.

public class QUser extends EntityPathBase<User> {
    public static final QUser user = new QUser("user");
    
    public final NumberPath<Long> id = createNumber("id", Long.class);
    public final StringPath name = createString("name");
    public final NumberPath<Integer> age = createNumber("age", Integer.class);
    
    // constructors and methods
}

이제 Querydsl을 사용하여 복잡한 쿼리를 작성해볼 시간입니다. 예를 들어, 18세 이상이며 이름이 “John”인 사용자를 조회하는 쿼리를 작성해보겠습니다.

QUser user = QUser.user;

JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);

List<User> result = queryFactory.selectFrom(user)
    .where(user.age.goe(18).and(user.name.eq("John")))
    .fetch();

위 코드에서 QUser.user를 통해 User 엔티티를 참조하고, JPAQueryFactory를 사용하여 쿼리를 작성합니다. selectFrom()을 통해 어떤 엔티티를 조회할 것인지 설정하고, where()를 통해 필터링 조건을 설정합니다. fetch() 메서드는 실행된 쿼리의 결과를 가져옵니다.

결론

Querydsl은 복잡한 쿼리 작성을 간결하고 직관적으로 만들어주는 훌륭한 도구입니다. 이 글에서는 Querydsl을 사용하여 복잡한 쿼리를 작성하는 방법을 알아보았습니다. Querydsl의 다양한 기능과 활용 방법은 공식문서를 참고하시기 바랍니다.