4

比較的単純なクエリが必要ですが、JPA のせいで作成が難しくなっています。

SQL バリアントは次のようになります。

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

[編集: OrderID は主キーではありません。テーブル内で等しい OrderId がさらに存在する可能性があります]

CustomerIDメソッドに渡される変数でを設定する必要があります。

ドキュメントを見つけましたCriteriaQuery distinct()が、すべてをまとめることができないようです。

これは私がこれまでに持っているものです:

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

1 に答える 1

11
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 ) );
于 2013-10-31T14:11:19.223 に答える