JPA Select Count Distinct [英] JPA Select Count Distinct
本文介绍了JPA Select Count Distinct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个相对简单的查询,但JPA很难创建它。
I need a relatively simple query, but JPA makes it kind of hard to create it.
SQL变体如下所示:
The SQL variant would look like this:
SELECT COUNT(DISTINCT OrderID) AS DistinctOrders FROM Orders WHERE CustomerID=7;
我需要用一个变量设置 CustomerID
传递给我的方法。
I need to set the CustomerID
with a variable that is passed to my method.
我找到了关于 CriteriaQuery的文档
distinct()
但我似乎无法将它们全部包装在一起。
I found documentation on CriteriaQuery
distinct()
but I can't seem to wrap it all together.
这是我到目前为止所做的:
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 ) );
这篇关于JPA Select Count Distinct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文