我正在尝试编写规范以限制findAll()存储库方法的返回值。 我可以添加groupBy和orderBy子句但不能使用sum聚合(没有错误但在查看的查询中看不到聚合结果SUM_TOTAL)。
这是我的代码:
public static Specification<Commande> searchCommandWith(final Long dId, final Long gId, final Long pId, final LocalDate date1, final LocalDate date2) {
return new Specification<Commande>() {
@Override
public Predicate toPredicate(Root<Commande> commandeRoot, CriteriaQuery<?> query, CriteriaBuilder cb) {
final List<Predicate> predicates = new ArrayList<Predicate>();
if(dId!=null && dId > 0 ) {
Predicate p = cb.equal(commandeRoot.get("d").get("id"), dId);
predicates.add(p);
}
if(gId!=null && gId > 0 ) {
Predicate p = cb.equal(commandeRoot.get("g").get("id"), gId);
predicates.add(p);
}
if(pId!=null && pId > 0 ) {
Predicate p = cb.equal(commandeRoot.get("p").get("id"), pId);
predicates.add(predicate3);
}
//TODO
if(date1!=null && date2!=null ) {
Path<LocalDate> date = commandeRoot.<LocalDate>get("date");
Predicate startPredicate = cb.greaterThanOrEqualTo(date, date1);
Predicate endPredicate = cb.or(cb.isNull(date), cb.lessThanOrEqualTo(date, date2));
Predicate p= cb.and(startPredicate, endPredicate);
predicates.add(p);
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
public static Specification<Commande> searchCommandWith( final String sumCol, final String groupBy, final String orderBy, ..) {
return new Specification<Commande>() {
@Override
public Predicate toPredicate(Root<Commande> commandeRoot, CriteriaQuery<?> query, CriteriaBuilder cb) {
if(sumCol!=null && !sumCol.isEmpty()){
Expression sumExp = cb.sum(commandeRoot.<Double>get(sumCol));
query.select(sumExp.alias("SUM_TOTAL"));
}
if(groupBy!=null && !groupBy.isEmpty()){
query.groupBy(commandeRoot.get(groupBy));
}
if(orderBy!=null && !orderBy.isEmpty()){
//query.orderBy(commandeRoot.get(orderBy));
query.orderBy(cb.desc(commandeRoot.get(orderBy)));
}
return searchCommandWith(delegueId, grossisteId, pharmacieId, dateDebut, dateFin).toPredicate(commandeRoot, query, cb);
}
};