2013-10-31 221 views
1

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

的SQL变种是这样的:

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

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

我需要设置CustomerID与传递给我的方法的变量。

我发现有关CriteriaQuerydistinct()的文档,但我似乎无法将它们全部包装在一起。

这是我到目前为止有:

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

JPQL? “SELECT COUNT(o.orderID)FROM订单o WHERE o.customerID =:customerID GROUP BY o.orderID” –

回答

6
CriteriaBuilder cb = this.em.getCriteriaBuilder(); 
CriteriaQuery<Long> c = builder.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)); 
+0

这是如何考虑'OrderId'的?我知道这是一个愚蠢的名字,但可能有更多的字段在'Order'中有一个类似的'OrderId'。我认为伯爵现在会过高? – RobAu

+0

如果'OrderId'是'Order'表中的主键,那么生成的SQL查询将完全采用该字段。那么:OrderId是表中的主键?当然,如果你想要的话,你可以检查生成/执行的查询(打开JPA提供程序中的日志记录或检查数据库级别的日志记录)。 –

+0

它不是。我创建了这个示例代码,因为我不能发布真实的代码。该表更像'OrderMutation',其中可以有多个'OrderId' – RobAu