JPA Select Count Distinct

时间:2013-10-31 13:14:59

标签: java sql jpa criteria

我需要一个相对简单的查询,但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<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 ) );

1 个答案:

答案 0 :(得分:6)

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 ) );