JPA Select Count Distinct

Rob*_*bAu 1 java sql jpa criteria

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

SQL变体看起来像这样:

SELECT COUNT(DISTINCT OrderID) AS DistinctOrders FROM Orders WHERE CustomerID=7;
Run Code Online (Sandbox Code Playgroud)

[编辑: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 ) );
Run Code Online (Sandbox Code Playgroud)

And*_*i I 7

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 ) );
Run Code Online (Sandbox Code Playgroud)