【问题标题】:JPA Select Count DistinctJPA 选择计数不同
【发布时间】:2013-11-11 12:26:46
【问题描述】:

我需要一个相对简单的查询,但是 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 ) );

【问题讨论】:

  • JPQL? "SELECT COUNT(o.orderID) FROM Orders o WHERE o.customerID = :customerID GROUP BY o.orderID"

标签: java sql jpa criteria


【解决方案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 ) );

【讨论】:

  • 如何考虑“OrderId”?我知道这是一个有点傻的名字,但“Order”中可能有更多具有类似“OrderId”的字段。我认为现在计数会太高?
  • 如果OrderIdOrder 表中的主键,那么生成的SQL 查询将使用该字段。那么:OrderId 是表中的主键吗?当然,如果您愿意,您可以检查生成/执行的查询(在您的 JPA 提供程序中打开日志记录或检查您的数据库级别的日志记录)。
  • 不是。我创建了这个示例代码,因为我无法发布真实代码。该表更像是“OrderMutation”,其中可以有多个“OrderId”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2015-11-11
  • 2018-09-02
  • 2014-04-03
相关资源
最近更新 更多