Java JPA选择计数不同

Java JPA选择计数不同,java,sql,jpa,criteria,Java,Sql,Jpa,Criteria,我需要一个相对简单的查询,但是JPA使得创建它有点困难 SQL变体如下所示: SELECT COUNT(DISTINCT OrderID) AS DistinctOrders FROM Orders WHERE CustomerID=7; [编辑:OrderID不是主键。表中可以有更多相等的OrderID] 我需要使用传递给我的方法的变量设置CustomerID 我在CriteriaQuerydistinct()上找到了文档,但我似乎无法将其全部打包 这就是我到目前为止所做的: Criteri

我需要一个相对简单的查询,但是JPA使得创建它有点困难

SQL变体如下所示:

SELECT COUNT(DISTINCT OrderID) AS DistinctOrders FROM Orders WHERE CustomerID=7;
[编辑:OrderID不是主键。表中可以有更多相等的OrderID]

我需要使用传递给我的方法的变量设置
CustomerID

我在
CriteriaQuery
distinct()
上找到了文档,但我似乎无法将其全部打包

这就是我到目前为止所做的:

CriteriaBuilder cb = this.em.getCriteriaBuilder();
CriteriaQuery<Order> c = cb.createQuery( Order.class );
Root<Order> order = c.from( Order.class );
Path<String> customerID = order.get( "customerID" );
c.where( cb.equal( customerID, theId ) );
CriteriaBuilder cb=this.em.getCriteriaBuilder();
CriteriaQuery c=cb.createQuery(Order.class);
根订单=c.from(order.class);
Path customerID=order.get(“customerID”);
c、 式中(cb.equal(customerID,theId));
CriteriaBuilder cb=this.em.getCriteriaBuilder();
CriteriaQuery c=cb.createQuery(Long.class)//查询返回一个长的而不是订单
根订单=c.from(order.class);
//c、 选择(cb.countDistinct(顺序))//这就是你要找的代码
c、 选择(cb.countDistinct(order.get(“orderID”))//用于计算主键以外的不同字段
Path customerID=order.get(“customerID”);
c、 式中(cb.equal(customerID,theId));

这是如何考虑到“订单ID”的?我知道这是一个有点傻的名字,但在“Order”中可能会有更多字段具有类似的“OrderId”。我认为现在计数会太高吗?如果
OrderId
Order
表中的主键,那么生成的SQL查询将恰好使用该字段。那么:OrderId是表中的主键吗?当然,如果您愿意,您可以检查生成/执行的查询(在您的JPA提供程序中打开日志记录或在您的DB级别上检查日志记录)。我创建这个示例代码是因为我不能发布真实的代码。该表更像是“OrderMutation”,其中可以有多个“OrderId”JPQL?“从订单o中选择计数(o.orderID),其中o.customerID=:customerID按o.orderID分组”
CriteriaBuilder cb = this.em.getCriteriaBuilder();
CriteriaQuery<Long> c = cb.createQuery(Long.class);//the query returns a long, and not Orders
Root<Order> order = c.from( Order.class );
//c.select(cb.countDistinct(order));//and this is the code you were looking for
c.select(cb.countDistinct(order.get("orderID")));//for counting distinct fields other than the primary key
Path<String> customerID = order.get( "customerID" );
c.where( cb.equal( customerID, theId ) );