JPA之Specification多条件搜索

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;


@Override
public Result> selectCashReceiptByCondition(CashReceiptQueryDTO query) {
	log.info("selectCashReceiptByCondition query:{}", JSON.toJSONString(query));
	// 1.校验参数
	query.check();
	// 2.获取查询条件
	Specification specification = getCashReceiptSpecification(query);
	Pageable pageable = getCashReceiptPageable(query);
	// 3.调用JPA,返回查询结果
	org.springframework.data.domain.Page page = cashReceiptRepository.findAll(specification, pageable);
	List cashReceiptList = page.getContent();
	return ResultUtils.success(new Page<>(query.getCurrentPage(), query.getPageSize(), cashReceiptList, page.getTotalElements()));
}

/*
 * 设置 JPA搜索的 specification
 */
private Specification getCashReceiptSpecification(CashReceiptQueryDTO query) {
	Specification specification = new Specification() {
		@Override
		public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
			List list = new ArrayList();
			// 简单单表查询
			if (!ObjectUtils.isEmpty(query.getReceiptStartDate()) && !ObjectUtils.isEmpty(query.getReceiptEndDate())) { // 收款时间
				Predicate p1 = cb.greaterThanOrEqualTo(root.get("receiptDate").as(Date.class), query.getReceiptStartDate());
				Predicate p2 = cb.lessThan(root.get("receiptDate").as(Date.class), query.getReceiptEndDate());
				list.add(cb.and(p1, p2));
			}
			if (!ObjectUtils.isEmpty(query.getPaymentWay())) {
				list.add(cb.equal(root.get("paymentWay").as(Byte.class), query.getPaymentWay())); // 支付渠道:0、未知,1、收银台,2、条码支付,3、扫码支付
			}
			return cb.and(list.toArray(new Predicate[0]));
		}
	};
	return specification;
}

/*
 * 设置 JPA 搜索 结果集的 排序 规则
 * 支持分页查询,支持多条件排序,多条件 升降序 混用 都支持
 */
private Pageable getCashReceiptPageable(CashReceiptQueryDTO query) {
	List orders = new ArrayList();
	orders.add(new Order(Sort.Direction.DESC, "inputDate"));
	orders.add(new Order(Sort.Direction.DESC, "receiptDate"));
	Pageable pageable = new PageRequest(query.getCurrentPage() - 1, query.getPageSize(), new Sort(orders));
	return pageable;
}

 

你可能感兴趣的:(JPA之Specification多条件搜索)