Spring-Data-Jpa 之时间段、某日期之前、生效、失效的涉及到时间的复杂查询
public static Specification<RechargeActivity> getSpecification(RechargeActivityReq req) {
return (root, query, builder) -> {
List<Predicate> predicates = new ArrayList<>();
predicates.add(builder.equal(root.get("storeId"), req.getStoreId()));
predicates.add(builder.equal(root.get("del"), false));
if (StringUtils.isNotBlank(req.getActivityName())) {
String keyword = req.getActivityName().trim() + "%";
predicates.add(builder.like(root.get("activityName"), keyword));
}
if (req.getStatus() != null) {
if (req.getStatus().equals(RechargeActivity.ACTIVITY_STATUS_PRE)) {
//未生效。1.生效日期之前 2.状态为ENABLE(0)
long now = System.currentTimeMillis();
predicates.add(builder.greaterThan(root.get("enableTime"), now));
predicates.add(builder.equal(root.get("activityStatus"), RechargeActivity.ACTIVITY_STATUS_ENABLE));
} else if (req.getStatus().equals(RechargeActivity.ACTIVITY_STATUS_ENABLE)) {
//生效中。1.生效日期之后 2.失效日期之前 3.状态为ENABLE(0)
long now = System.currentTimeMillis();
predicates.add(builder.lessThan(root.get("enableTime"), now));
predicates.add(builder.greaterThan(root.get("disableTime"), now));
predicates.add(builder.equal(root.get("activityStatus"), RechargeActivity.ACTIVITY_STATUS_ENABLE));
} else if (req.getStatus().equals(RechargeActivity.ACTIVITY_STATUS_DISABLE)) {
//已失效。1.失效日期之后
long now = System.currentTimeMillis();
predicates.add(builder.or(
builder.equal(root.get("activityStatus"), RechargeActivity.ACTIVITY_STATUS_DISABLE),
builder.and(builder.equal(root.get("activityStatus"), RechargeActivity.ACTIVITY_STATUS_ENABLE),
builder.lessThan(root.get("disableTime"), now)),
builder.and(builder.equal(root.get("activityStatus"), RechargeActivity.ACTIVITY_STATUS_PAUSE),
builder.lessThan(root.get("disableTime"), now))));
} else if (req.getStatus().equals(RechargeActivity.ACTIVITY_STATUS_PAUSE)) {
//已暂停。1.状态为PAUSE(2)
predicates.add(builder.equal(root.get("activityStatus"), RechargeActivity.ACTIVITY_STATUS_PAUSE));
}
}
Predicate[] p = new Predicate[predicates.size()];
return builder.and(predicates.toArray(p));
};
}