CriteriaBuilder jpa 日期date查询
概要:前端日期选择器选择完之后传一个String到后台,后台的字段的数据类型是date
前端:
<label class="layui-form-label" >单据日期</label> <div class="layui-input-inline"> <input type="text" id="taxDate" placeholder="单据日期" autocomplete="off" class="layui-input"> </div>
//单据日期 laydate.render({ elem: '#taxDate' ,type: 'date' //默认,可不填 });
后端:
@Override public Page<SalesOrder> findPage(SalesOrderModel salesOrderModel, int currentPage, int pageSize) { Specification<SalesOrder> specification = new Specification<SalesOrder>() { @Override public Predicate toPredicate(Root<SalesOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<>(); Predicate deleteMark = cb.equal(root.get("deleteMark").as(Boolean.class), false); list.add(deleteMark); // 单据编号 if (!CommonUtil.isEmpty(salesOrderModel.getOrderId())) { Predicate orderId = cb.like(root.get("orderId"), "%" + salesOrderModel.getOrderId().trim() + "%"); list.add(orderId); } // 内部编号 if (!CommonUtil.isEmpty(salesOrderModel.getEntryId())) { Predicate entryId = cb.like(root.get("entryId"), "%" + salesOrderModel.getEntryId().trim() + "%"); list.add(entryId); } // 单据日期 if (!CommonUtil.isEmpty(salesOrderModel.getTaxDate())) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = null; Date endDate = null; try { startDate = format.parse(salesOrderModel.getTaxDate()); endDate = format.parse(salesOrderModel.getTaxDate()); } catch (ParseException e) {
startDate = new Date();
endDate = new Date();
}
Predicate taxDate = cb.between(root.<Date>get("taxDate"),startDate, endDate);//开始日期和结束日期是同一个 list.add(taxDate);
}
if(!CommonUtil.isEmpty(sapOrderModel.getStartTime()) && !CommonUtil.isEmpty(sapOrderModel.getEndTime())){
//起始日期
Predicate startTime = cb.greaterThanOrEqualTo(root.get("docDate").as(String.class), sapOrderModel.getStartTime());
list.add(startTime);
//结束日期
Predicate endTime = cb.lessThanOrEqualTo(root.get("docDate").as(String.class), sapOrderModel.getEndTime());
list.add(endTime);
}
Predicate[] predicates = new Predicate[list.size()]; return cb.and(list.toArray(predicates));
} };
List<Order> orders = new ArrayList<>(); orders.add(new Order(Direction.DESC, "createDate"));
Sort sort = Sort.by(orders); Pageable pageable = PageRequest.of(currentPage - 1, pageSize, sort);
return salesOrderRepository.findAll(specification, pageable);
}