jpa2 subquery

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
		Root<Order> root = criteriaQuery.from(Order.class);
		Path<Object> path = root.get("id"); // field to map with sub-query
		//
		criteriaQuery.select(root);
		Subquery<Order> subquery = criteriaQuery.subquery(Order.class);
		Root<OrderItem> fromProject = subquery.from(OrderItem.class);
		subquery.select(fromProject.<Order>get("order")); // field to map with main-query
		Predicate restrictions = criteriaBuilder.conjunction();
		if(productCategory != null) {
			if(productCategory.getId() == 1) {//浴桶
				subquery.where(criteriaBuilder.equal(fromProject.get("product").get("productCategory").get("id"), 1));
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.in(path).value(subquery));
			} else {
				subquery.where(criteriaBuilder.equal(fromProject.get("product").get("productCategory").get("id"), 1));
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(criteriaBuilder.in(path).value(subquery)));
			}
		}
		if (beginDate != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
		}
		if (endDate != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date> get("createDate"), endDate));
		}
		if (orderStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}
		if (paymentStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentStatus"), paymentStatus));
		}
		if (shippingStatus != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("shippingStatus"), shippingStatus));
		}
		if (shops != null && !shops.isEmpty()) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.in(root.get("shop")).value(shops));
		}
		if (hasExpired != null) {
			if (hasExpired) {
				restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(), criteriaBuilder.lessThan(root.<Date> get("expire"), new Date()));
			} else {
				restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThanOrEqualTo(root.<Date> get("expire"), new Date())));
			}
		}
		criteriaQuery.where(restrictions);

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值