JPA Select Count Distinct

我需要一个相对简单的查询,但JPA很难创建它。

SQL变体看起来像这样:

SELECT COUNT(DISTINCT OrderID) AS DistinctOrders FROM Orders WHERE CustomerID=7; 

[编辑:OrderID不是主键。 可以有更多的OrderId在表中等于]

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

我在CriteriaQuery distinct()上找到了文档,但我似乎无法将它们全部包装在一起。

这是我到目前为止:

 CriteriaBuilder cb = this.em.getCriteriaBuilder(); CriteriaQuery c = cb.createQuery( Order.class ); Root order = c.from( Order.class ); Path customerID = order.get( "customerID" ); c.where( cb.equal( customerID, theId ) ); 

 CriteriaBuilder cb = this.em.getCriteriaBuilder(); CriteriaQuery c = cb.createQuery(Long.class);//the query returns a long, and not Orders Root 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 customerID = order.get( "customerID" ); c.where( cb.equal( customerID, theId ) );