JPA에서 일반적으로 사용하는 Method Query에 QueryDSL을 연동
1. QuerydslPredicateExecutor
Predicate를 JpaRepository에서 추출할 수 있도록 해줌
public interface ProductRespository extends JpaRepository<ProductEntity, UUID>,
ProductRepositoryCustom,
QuerydslPredicateExecutor<ProductEntity>
{
}
@GetMapping
public ResponseEntity<ResProductGetDtoApiV1> getProductList(
@QuerydslPredicate(root = ProductEntity.class) Predicate predicate,
@PageableDefault(sort = "id", direction = Direction.DESC) Pageable pageable
) {
return ResponseEntity.ok(productService.getProductList(predicate, pageable)
);
}
@Override
@Transactional(readOnly = true)
public ResProductGetDtoApiV1 getProductList(Predicate predicate, Pageable pageable) {
Page<ProductEntity> productEntityPage = productRepository.findAll(predicate, pageable);
return ResProductGetDtoApiV1.of(productEntityPage);
}
2. BooleanBuilder
BooleanBuilder도 Predicate임
만약 id가 1, 2, 3인 상품을 검색하고 싶다면?
id=1,2,3 안됨
@GetMapping
public ResponseEntity<ResProductGetDtoApiV1> getProductList(
@RequestParam(required = false) List<Long> idList,
@QuerydslPredicate(root = ProductEntity.class) Predicate predicate,
@PageableDefault(sort = "id", direction = Direction.DESC) Pageable pageable
) {
return ResponseEntity.ok(productService.getProductList(predicate, pageable)
);
}
@Override
@Transactional(readOnly = true)
public ResProductGetDtoApiV1 getProductList(List<Long> idList, Predicate predicate, Pageable pageable) {
BooleanBuilder bb = new BooleanBuilder(predicate);
if(!idList.isEmpty() && idList != null) {
bb.and(productEntity.id.in(idList));
}
bb.and(productEntity.stock.gt(0));
Page<ProductEntity> productEntityPage = productRepository.findAll(bb, pageable);
return ResProductGetDtoApiV1.of(productEntityPage);
}
3. QuerydslBinderCustomizer
추출된 Predicate의 조건을 수정할 수 있음
1, 2번은 문자 검색 시 equals 조건만 검색
QuerydslBinderCustomizer는 contains 조건으로 바꿀 수 있음
public interface ProductRepositoryV2 extends JpaRepository<ProductEntity, UUID>,
ProductRepositoryCustom,
QuerydslPredicateExecutor<ProductEntity>,
QuerydslBinderCustomizer<QProductEntity> {
@Override
default void customize(QuerydslBindings bindings, @NotNull QProductEntity qProductEntity) {
bindings.bind(String.class).all((StringPath path, Collection<? extends String> values) -> {
List<String> valueList = new ArrayList<>(values.stream().map(String::trim).toList());
if (valueList.isEmpty()) {
return Optional.empty();
}
BooleanBuilder bb = new BooleanBuilder();
for (String s : valueList) {
bb.or(path.containsIgnoreCase(s));
}
return Optional.of(bb);
});
}
}
'DB > QueryDsl' 카테고리의 다른 글
[QueryDSL] 대용량 최적화 (0) | 2025.04.24 |
---|---|
[QueryDSL] 설정 (1) | 2025.04.24 |
QueryDSL (0) | 2025.04.23 |