[java] Querydsl을 사용하여 인메모리 데이터베이스와 통합 사용하기

Querydsl은 자바 언어로 작성된 오픈 소스 프레임워크로, 데이터베이스 쿼리를 타입 안전하게 작성하고 실행할 수 있는 기능을 제공합니다. 이 글에서는 Querydsl을 사용하여 인메모리 데이터베이스와 통합하는 방법에 대해 설명하겠습니다.

1. Querydsl 설정

먼저 Querydsl을 프로젝트에 추가해야 합니다. Maven 프로젝트를 사용하는 경우, pom.xml 파일에 다음 의존성을 추가합니다:

<dependencies>
    <!-- Querydsl 의존성 -->
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-core</artifactId>
        <version>5.0.0</version>
    </dependency>
</dependencies>

Gradle 프로젝트를 사용하는 경우, build.gradle 파일에 다음 의존성을 추가합니다:

dependencies {
    // Querydsl 의존성
    implementation 'com.querydsl:querydsl-core:5.0.0'
}

2. 인메모리 데이터베이스 설정

Querydsl은 다양한 데이터베이스와 통합할 수 있습니다. 이 예제에서는 인메모리 데이터베이스인 H2를 사용하겠습니다. H2를 프로젝트에 추가하기 위해 Maven 프로젝트의 pom.xml 파일에 다음 의존성을 추가합니다:

<dependencies>
    <!-- H2 인메모리 데이터베이스 의존성 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.200</version>
    </dependency>
</dependencies>

Gradle 프로젝트의 경우, build.gradle 파일에 다음 의존성을 추가합니다:

dependencies {
    // H2 인메모리 데이터베이스 의존성
    implementation 'com.h2database:h2:1.4.200'
}

3. Querydsl 사용하기

이제 Querydsl과 H2를 설정했으므로, 실제로 데이터베이스와 통합하여 쿼리를 실행해보겠습니다. 예를 들어, “users”라는 테이블에서 이름이 “John”인 사용자를 조회하는 쿼리를 작성해보겠습니다.

package com.example;

import com.querydsl.core.types.dsl.*;
import com.querydsl.sql.*;

public class Main {
    public static void main(String[] args) {
        // 데이터베이스 연결 설정
        com.querydsl.sql.Configuration configuration = new com.querydsl.sql.Configuration(new H2Templates());
        com.querydsl.sql.SQLQueryFactory queryFactory = new com.querydsl.sql.SQLQueryFactory(configuration, new com.querydsl.sql.H2Connection(ConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "")));

        // Querydsl 쿼리 작성
        QUser qUser = QUser.user;
        com.querydsl.core.types.Predicate predicate = qUser.name.eq("John");
        com.querydsl.sql.SQLQuery<User> query = queryFactory.selectFrom(qUser).where(predicate);

        // 쿼리 실행
        List<User> users = query.fetch();

        // 결과 출력
        for (User user : users) {
            System.out.println(user.getName());
        }
    }
}

위의 예제 코드에서는 Querydsl의 QUser 클래스를 사용하여 테이블과 필드를 타입 안전하게 작성하고, SQLQueryFactory를 사용하여 데이터베이스와 연결한 후 쿼리를 작성하고 실행합니다.

이제 인메모리 데이터베이스와 Querydsl을 통합하여 쿼리를 실행하는 방법을 알았습니다. 이를 활용하여 복잡한 데이터베이스 조작 작업을 보다 쉽고 안전하게 수행할 수 있습니다.

참고자료