Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ) );
like image 246
Rob Audenaerde Avatar asked Dec 19 '22 22:12

Rob Audenaerde


1 Answers

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 ) );
like image 140
V G Avatar answered Jan 09 '23 08:01

V G