JPA Select Count Distinct

♀尐吖头ヾ 提交于 2019-12-05 07:29:31

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/19707529/jpa-select-count-distinct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!