4

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

1 回答 1

11
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 ) );
于 2013-10-31T14:11:19.223 回答