简体   繁体   English

JPA选择计数不同

[英]JPA Select Count Distinct

I need a relatively simple query, but JPA makes it kind of hard to create it. 我需要一个相对简单的查询,但是JPA使其很难创建。

The SQL variant would look like this: SQL变量如下所示:

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

[Edit: OrderID is NOT the primary key. [编辑:OrderID不是主键。 There can be more OrderId that are equals in the table] 表中可以有更多等于的OrderId]

I need to set the CustomerID with a variable that is passed to my method. 我需要使用传递给我的方法的变量设置CustomerID

I found documentation on CriteriaQuery distinct() but I can't seem to wrap it all together. 我找到了有关CriteriaQuery distinct()文档,但似乎无法将它们全部包装在一起。

This is what I have so far: 这是我到目前为止的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM