I want to extend this Specification by adding order by params.
Search options 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);
}
I tried this:
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);
}
I can't find a solution how to implement this. Can you give me advice where I'm wrong?