본문 바로가기

Spring/JPA

4) Spring Data JPA 4부 - QueryDSL Predicate 활용

반응형

앞에서 간단히 QueryDsl 사용법에 대해 알아 봤는데 . 

요기서 조금더 실무에서 자주 쓰이는 방법에 공부해 보자.

Predicate 를 직역하면 "서술어" 라고 하는데 즉 where 에 들어가는 조건문을 나타낸다고 생각하면 된다.

 

Predicate 는 보통 where 문을 작성할때 Parameter의 Type 및 값 유무에 따라 조건을 다르게 하고 싶을 사용하게 된다. 

아래 샘플 Predicate 를 참조.

package com.devracoon.jpa.repository;

import com.devracoon.jpa.entity.QItem;
import com.devracoon.jpa.entity.QProduct;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.JPAExpressions;
import org.apache.commons.lang3.StringUtils;

import java.util.function.Predicate;

public class SamplePredicate {

    public static BooleanBuilder productPredicate(String productName , String itemName){
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QProduct product = QProduct.product;
        QItem item = QItem.item;
        if(StringUtils.isNotEmpty(productName)){
            booleanBuilder.and(product.productName.like("%" + productName + "%"));
        }

        if(StringUtils.isNotEmpty(itemName)){
            booleanBuilder.and(product.items.any().itemName.like("%" + itemName + "%"));
        }

        return booleanBuilder;
    }
}
package com.devracoon.jpa.repository;

import com.devracoon.jpa.entity.Product;
import com.devracoon.jpa.entity.QProduct;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;

import java.util.List;

public class ProductRepositoryCustomImpl extends QuerydslRepositorySupport implements ProductRepositoryCustom{

    private JPAQueryFactory queryFactory;

    public ProductRepositoryCustomImpl(JPAQueryFactory queryFactory) {
        super(Product.class);
        this.queryFactory = queryFactory;
    }

    public List<Product> findProductByCustom(String productName , String itemName){
        QProduct product = QProduct.product;
        List<Product> products = queryFactory.selectFrom(product).leftJoin(product.items).fetchJoin()
                .where(SamplePredicate.productPredicate(productName,  itemName)).fetch();

        return products;
    }




}

아주 짧은 간단한 소스이지만 꽤 자주 사용하는 코드들이다.

만일 customRepository에서  여러개의 find 함수에서 여러 조건에 따라 쿼리를 보내야 한다고 생각하면 

각각 함수에서 where 문 앞의 조건들을 if 처리를 하면서 작성해야 하는데 이렇게 되면 코드 중복도 문제지만 너무 길어지는 코드로 인해 

가독성이 떨어지게 된다.

 

이해를 위하 코드 재사용성을 위해 조건문을 같이 사용하고자 하는 목적이 바로 Predicate  이다.

 

 다음은 QueryDsl Pagsing 에 대해 알아보자