JPA选择计数唯一值

4

我需要一个相对简单的查询,但是JPA使其有些难以创建。

这个SQL查询看起来像这样:

SELECT COUNT(DISTINCT OrderID) AS DistinctOrders FROM Orders WHERE CustomerID=7;
< p >【编辑: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 ) );

1
JPQL是什么?"SELECT COUNT(o.orderID) FROM Orders o WHERE o.customerID = :customerID GROUP BY o.orderID" - Sami Korhonen
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 ) );

这个如何考虑“OrderId”?我知道这个名字有点傻,但是“Order”中可能会有更多类似“OrderId”的字段。我想现在计数会变得太高了吧? - Rob Audenaerde
如果 OrderIdOrder 表的主键,那么生成的 SQL 查询将仅取该字段。所以:OrderId 在表中是主键吗?当然,如果你想要检查生成/执行的查询语句,可以在 JPA 提供者中打开日志记录或检查数据库级别的日志记录。 - V G
不是。我创建了这个示例代码,因为我不能发布真实代码。该表更像“OrderMutation”,其中可能会有多个“OrderId”。 - Rob Audenaerde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接