JPA Criteria子查询整理:表达式中的查询键无效

时间:2016-08-28 03:12:42

标签: jpa subquery eclipselink collate

我正在使用ecliselink,并尝试将本机SQL转换为包含子查询的Criteria API,但是获得了与子查询的排序规则相关的异常。

使用子查询从项目价格计算销售订单总额:

public class SalesOrder {
   BigDecimal totalPrice;
   public List<OrderItem> orderItems;

}

public class OrderItem {

   SalesOrder salesOrder;
   BigDecimal itemPrice;
}

update SalesOrder so set so.total=(select sum(itemPrice) from OrderItem oi where oi.salesOrderId=so.id);

使用Criteria API转换更新查询

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaUpdate<SalesOrder> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(SalesOrder.class);

Root<SalesOrder> root = criteriaUpdate.from(SalesOrder.class);

Subquery<BigDecimal> subquery = criteriaUpdate.subquery(BigDecimal.class);
Root<InventoryForm> subqueryRoot = subquery.correlate(root);
Expression<BigDecimal> itemPricePath = subqueryRoot.join("orderItems", JoinType.LEFT).get("itemPrice");
subquery.select(criteriaBuilder.sum(itemPricePath));

Path<BigDecimal> totalPricePath = root.get("totalPrice");
criteriaUpdate.set(totalCostPath, subquery);

em.createQuery(criteriaUpdate).executeUpdate(); 

得到错误:

org.eclipse.persistence.exceptions.QueryException
Exception Description: Invalid query key [orderItems] in expression.
Query: UpdateAllQuery(referenceClass=SalesOrder )
    at org.eclipse.persistence.exceptions.QueryException.invalidQueryKeyInExpression(QueryException.java:696)
    at org.eclipse.persistence.internal.expressions.QueryKeyExpression.validateNode(QueryKeyExpression.java:1009)
    at org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3275)
    at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:369)
    at org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:756)
    at org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:669)
    at org.eclipse.persistence.internal.expressions.SQLSelectStatement.normalize(SQLSelectStatement.java:1461)
    at org.eclipse.persistence.internal.expressions.SubSelectExpression.normalizeSubSelect(SubSelectExpression.java:205)

0 个答案:

没有答案