JPAのSpecificationマルチ条件検索

2785 ワード

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;
}