简体   繁体   中英

JPA Select Count Distinct

I need a relatively simple query, but JPA makes it kind of hard to create it.

The SQL variant would look like this:

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

[Edit: OrderID is NOT the primary key. There can be more OrderId that are equals in the table]

I need to set the CustomerID with a variable that is passed to my method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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