TIL

2_5.QueryDSL 활용

꿀승 2025. 1. 10. 15:21
728x90
반응형
SMALL

학습내용

  1. QueryProjection
  2. 실습

학습정리

1. QueryProjection 사용하기

  • QueryProjection이란 ?

    • QueryDSL에서 DTO에 데이터를 매핑하기 위한 방법
    • DTO 클래스에 @QueryProjection 에너테이션을 추가하여 매핑 지원
  • 예시

    @Getter
    @Builder
    @FieldDefaults(level = AccessLevel.PRIVATE)
    public class ProductResponse {
    
      String name;
      String description;
      BigDecimal price;
      Integer stock;
    
    //해당 에너테이션 생성자에 추가
    // 빌드시에 build/generated/sources/annotationProcessor 해당 Q클래스 생성
      @QueryProjection 
      public ProductResponse(
          String name,
          String description,
          BigDecimal price,
          Integer stock
      ) {
        this.name = name;
        this.description = description;
        this.price = price;
        this.stock = stock;
      }
    }
    @Repository
    @RequiredArgsConstructor
    public class ProductQueryRepository {
    
      private final JPAQueryFactory queryFactory;
    
      public List<ProductResponse> search(String name, BigDecimal minPrice, BigDecimal maxPrice) {
        return queryFactory
            .select(
                //위에서 @QueryProjection 으로 생선된 Q클래스로 반환
                new QProductResponse(
                    product.name,
                    product.description,
                    product.price,
                    product.stock
            ))
            .from(product)
            .where(
                equalName(name),
                betweenPrice(minPrice, maxPrice)
            )
            .fetch();
      }
    }

참고 자료

728x90
반응형
LIST