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

 项目示例

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 specification = new Specification() {
        @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 page = workRep.findAll(specification, pageRequest);

 

你可能感兴趣的:(#,数据持久层,JPA时间段)