将orderby排序添加到搜索规范中

vdzxcuhz  于 2021-07-22  发布在  Java
关注(0)|答案(2)|浏览(217)

我想通过添加orderbyparams来扩展这个规范。
搜索选项dto:

public class ProductSearchParams {
    private String title;
    private String type;
    private LocalDateTime publishedAt;
    private String sort;
    private List<String> sortBy;
}

public Page<ProductFullDTO> findProducts(ProductSearchParams params, Pageable pageable) {
        Specification<Product> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (params.getTitle() != null) {
                predicates.add(cb.equal(root.get("title"), params.getTitle()));
            }
            if (params.getType() != null) {
                predicates.add(cb.equal(root.get("type"), params.getType()));
            }
            if (params.getPublishedAt() != null) {
                predicates.add(cb.greaterThan(root.get("publishedAt"), params.getPublishedAt()));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return productService.findAll(spec, pageable).map(productMapper::toFullDTO);
    }

我试过这个:

public Page<ProductFullDTO> findProducts(ProductSearchParams params, Pageable pageable) {
        Specification<Product> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (params.getTitle() != null) {
                predicates.add(cb.equal(root.get("title"), params.getTitle()));
            }
            if (params.getType() != null) {
                predicates.add(cb.equal(root.get("type"), params.getType()));
            }
            if (params.getPublishedAt() != null) {
                predicates.add(cb.greaterThan(root.get("publishedAt"), params.getPublishedAt()));
            }
            if (params.getPublishedAt() != null) {
                predicates.add(cb.greaterThan(root.get("publishedAt"), params.getPublishedAt()));
            }
            query.orderBy(builder.desc((root.join(Prodotto_.listaQuoteIng))
                    .get(QuotaIngrediente_.perc_ing)));

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return productService.findAll(spec, pageable).map(productMapper::toFullDTO);
    }

我找不到一个解决办法来实现这个。你能告诉我哪里错了吗?

pcrecxhr

pcrecxhr1#

重新创建 pageable 调用前对象 findAll 方法:

// sort = "desc" sortBy = ["listaQuoteIng.perc_ing"]
List<Sort.Order> orders = params.getSortBy().stream().map(s -> new Sort.Order("asc".equals(params.getSort()) ? ASC : DESC, s)).collect(Collectors.toList());
pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(orders));
7gcisfzg

7gcisfzg2#

你是在问如何使用 sortBy 列表以指定排序顺序?以下应起作用:

query.orderBy(sortyBy.stream()
    .map(root::get)
    .map(cb::desc)
    .toList());

您还可以将排序顺序传递给 Pageable 通过 sort 查询参数(例如。 sort=name,asc&sort=type,desc&sort=listaQuoteIng.perc_ing,desc )并很容易地将其调整为标准api,请参阅以下答案。

相关问题