假設(shè)有表OnlineOrder(訂單表) 和 OnlineOrderDetail(訂單詳情表)垮抗, 首先可以構(gòu)建 Specification, 在查詢時(shí)氏捞,使用Join。
Specification<OnlineOrder> specification = (root, query, cb) -> {
List<Predicate> predicates = Lists.newArrayList();
// join構(gòu)建冒版,默認(rèn)時(shí)inner join
Join<OnlineOrder, OnlineOrderDetail> join = root.join("details");
Predicate detailP1 = cb.isNull(join.get("afterSaleAt"));
Predicate detailP2 = cb.equal(join.get("saleIsFinished").as(Boolean.class), true);
predicates.add(cb.or(detailP1, detailP2));
// distinct 去重
query.distinct(true);
// 已收貨訂單
predicates.add(cb.equal(root.get("orderStatus").as(String.class), OnlineOrderStatus.received.name()));
// 收貨時(shí)間早于7天前
predicates.add(cb.lessThan(root.get("receivedAt").as(LocalDateTime.class), day7Ago));
predicates.add(cb.isNull(root.get("billNo").as(String.class)));
// 過(guò)濾掉不看的單子
List<String> filters = criteria.getFilters();
if (!CollectionUtils.isEmpty(filters)) {
predicates.add(cb.not(root.get("orderNo").in(filters)));
}
Expression<LocalDateTime> createdAt = root.get("createdAt").as(LocalDateTime.class)液茎;
// 開(kāi)始時(shí)間
if (criteria.getBeginTime() != null) {
Predicate p = cb.greaterThanOrEqualTo(createdAt, criteria.getBeginTime().atStartOfDay());
predicates.add(p);
}
// 結(jié)束時(shí)間
if (criteria.getEndTime() != null) {
Predicate p = cb.lessThanOrEqualTo(createdAt, criteria.getEndTime().atStartOfDay());
predicates.add(p);
}
query.where(cb.and(predicates.toArray(new Predicate[0])));
query.orderBy(cb.desc(createdAt));
return query.getRestriction();
};
return specification;
}
下面是使用代碼:
Specification<OnlineOrder> specification = this.buildSpecification(criteria);
return onlineOrderRepository.findAll(specification);
OnlineOrderRepository 代碼如下:
public interface OnlineOrderRepository extends JpaRepository<OnlineOrder, String>, JpaSpecificationExecutor<OnlineOrder> {
}