Sring Data JPA使用Predicate进行模糊查询、按时间段查询

10 : demoDTO.getSize();PageRequest pageRequest = new PageRequest;Specification<W

Integer num = demoDTO.getNum() == null ? 0 : demoDTO.getNum();
Integer size = demoDTO.getSize() == null ? 10 : demoDTO.getSize();
		
PageRequest pageRequest = new PageRequest(num, size, new Sort(Sort.Direction.DESC, "userId"));
Specification<WorkOrderDO> specification = new Specification<WorkOrderDO>() {
        @Override
	public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
		Predicate predicate = cb.conjunction();
                //模糊查询
		if (demoDTO.getNum() != null) {
			predicate.getExpressions().add(cb.like(root.get("num"), "%" + demoDTO.getNum() + "%"));
		}
                //准确查询
		if (demoDTO.getName() != null) {
			predicate.getExpressions().add(cb.equal(root.get("name"), demoDTO.getName()));
		}
		String startTime = demoDTO.getStart();
		String endTime = demoDTO.getEnd();
		//起始日期
		if (startTime != null && !startTime.trim().equals("")) {
                        //时间大于
			predicate.getExpressions()
		.add(cb.greaterThanOrEqualTo(root.get("time").as(String.class), startTime));
		}
		//结束日期
		if (endTime != null && !endTime.trim().equals("")) {
                        //时间小于
			predicate.getExpressions()
		.add(cb.lessThanOrEqualTo(root.get("time").as(String.class), endTime + " 23:59:59"));
		}
		return predicate;
	}
};
Page<WorkOrderDO> page = workRep.findAll(specification, pageRequest);

发表评论

登录 后才能评论