BE/Spring & Spring Boot

[Spring Boot] Specification과 QueryDSL

baek-dev 2025. 1. 18. 12:50

1. JPA Specification

 

개념

Spring Data JPA에서 제공하는 동적 쿼리 작성 기능.

Java 객체 기반으로 조건을 조합하며, Criteria API를 내부적으로 활용.

복잡한 쿼리를 작성하면서도, 조건을 재사용할 수 있도록 설계되었다.

 

구성 요소

Specification<T> 인터페이스: 동적 쿼리의 조건을 정의.

Predicate: 조건문을 의미하며, CriteriaBuilder를 통해 생성.


Specification의 주요 메서드

toPredicate()

동적 쿼리의 핵심 메서드로, 필터 조건을 정의.

 

기본 형태

Specification<Entity> specification = (root, query, criteriaBuilder) -> {
    // 조건 정의
    return criteriaBuilder.equal(root.get("columnName"), "value");
};

Specification 사용 예제

 

1) 기본 필터 조건

import org.springframework.data.jpa.domain.Specification;

public class EntitySpecifications {
    public static Specification<Entity> hasName(String name) {
        return (root, query, criteriaBuilder) -> 
            criteriaBuilder.equal(root.get("name"), name);
    }
}

 

2) 필터 조합

Specification<Entity> spec = 
    EntitySpecifications.hasName("John")
    .and(EntitySpecifications.isActive(true));

 

3) JPA Repository에서 사용

List<Entity> results = entityRepository.findAll(spec);

장점

Spring Data JPA와 통합이 쉬움.

조건 재사용 가능.

 

단점

복잡한 쿼리 작성 시 코드가 길고 가독성이 떨어짐.

QueryDSL보다 표현력이 제한적.


2. QueryDSL

 

개념

동적 쿼리 작성을 위한 라이브러리로, 타입 세이프한 방식으로 쿼리를 작성할 수 있음.

JPA, SQL, MongoDB 등 다양한 데이터베이스와 통합 가능.

Spring Data JPA와 함께 사용하면 강력한 동적 쿼리 작성 기능을 제공.


구성 요소

1. Q클래스:

QueryDSL은 엔티티마다 자동으로 Q 접두사가 붙은 클래스를 생성(QEntity).

이 클래스를 사용하여 쿼리를 작성.

2. JPAQueryFactory:

쿼리를 작성하고 실행하기 위한 주요 클래스.


QueryDSL 사용 예제

 

1) 의존성 추가

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
    <version>5.0.0</version>
</dependency>
<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-apt</artifactId>
    <version>5.0.0</version>
    <scope>provided</scope>
</dependency>

2) Q클래스 생성

Maven/Gradle에서 annotationProcessor를 사용하여 Q클래스를 생성.

Maven:

<annotationProcessorPaths>
    <path>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>5.0.0</version>
    </path>
</annotationProcessorPaths>

 

Gradle:

annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jpa"

3) 기본 사용법

import com.querydsl.jpa.impl.JPAQueryFactory;

public List<Entity> findEntities(String name) {
    QEntity qEntity = QEntity.entity;
    return jpaQueryFactory
        .selectFrom(qEntity)
        .where(qEntity.name.eq(name))
        .fetch();
}

장점

타입 세이프한 코드 작성 가능 → 컴파일 시점에 오류를 잡을 수 있음.

간결하고 가독성이 높은 동적 쿼리 작성.

조인 및 복잡한 쿼리에 강력한 기능 제공.

 

단점

추가 설정(의존성, Q클래스 생성)이 필요.

초기 학습 곡선이 있음.


특징 JPA Specification QueryDSL
코드 가독성 조건이 많을수록 복잡해짐 가독성이 뛰어남
유지보수성 조건 재사용 가능 재사용성 뛰어남
타입 세이프성 보장되지 않음 보장됨
복잡한 쿼리 작성 가능하지만 코드가 길어짐  간단하고 직관적으로 작성 가능
설정 별도 설정 불필요  의존성 및 Q클래스 생성 필요
Spring 통합 Spring Data JPA와 기본적으로 통합 별도의 통합 필요

정리

간단한 조건 조합이 필요하거나 Spring Data JPA 환경에 익숙하다면 JPA Specification을 사용하는 것이 적합.

타입 세이프한 코드 작성이 중요하거나, 복잡한 동적 쿼리를 자주 작성한다면 QueryDSL이 더 강력하고 편리.

 

 

 

 

출처 : ChatGPT

'BE > Spring & Spring Boot' 카테고리의 다른 글

[Spring Boot] Swagger와 OpenAPI  (0) 2025.01.22
[Spring Boot] MockMvc  (0) 2025.01.20
[Spring Boot] List<Sort.Order>와 Sort.Order.desc()  (0) 2025.01.17
[Spring Boot, JPA] EntityManager  (1) 2025.01.16
[Spring Boot] @ControllerAdvice  (0) 2025.01.09