【问题标题】:Get min and max column values with single query使用单个查询获取最小和最大列值
【发布时间】:2018-12-27 05:52:56
【问题描述】:

如何通过使用 jpa 而不是使用本机查询来获取 minmax 值?

结果必须通过单个事务获取。

相对sql查询:

SELECT min(price), max(price) FROM product

我尝试使用此代码

criteria.setProjection(Projections.min("price"));
Integer min = (Integer) criteria.uniqueResult();
...
criteria.setProjection(Projections.max("price"));
Integer max = (Integer) criteria.uniqueResult();

但这似乎太奇怪了,无法执行两次。

【问题讨论】:

    标签: java hibernate entity jpa-2.0 criteria


    【解决方案1】:

    使用投影列表:

    criteria.setProjection(
      Projections.projectionList()
        .add(Projections.min("price"))
        .add(Projections.max("price"))
    );
    

    【讨论】:

      【解决方案2】:

      你需要在 Criteria 中使用 ProjectionList

      您的代码如下所示:

      criteria.setProjection(
           Projections.projectionList()
          .add(Projections.min("price"))
          .add(Projections.max("price"))
      );
      Object[] minMax = criteria.uniqueResult();
      Integer min = (Integer) minMax[0];
      Integer max = (Integer) minMax[1];
      

      另一种选择是使用 HQL,带有 minmax Aggregate functions

      Query q = session.createQuery("select min(prd.price), max(prd.price) from Product prd");
      Object[] minMax = q.getSingleResult();
      Integer min = (Integer) minMax[0];
      Integer max = (Integer) minMax[1];
      

      【讨论】:

      • 我更喜欢使用ProjectionList,但现在我的问题是如何将最低最高价格直接映射到生产实体,有两个关于属性minPricemaxPrice;我是否尝试过criteria = session.createCriteria(Product.class) 但没有成功。
      • @TheHunter 能否请您更新您的问题,与您的实体?您是否有一个 Product 实体并且想要获得另一个实体作为结果?
      • 抱歉错字,我更愿意将结果映射到实体Product,如果不可能,那么不用担心@chŝdk - 感谢您的回答,这就是我所需要的。
      猜你喜欢
      • 2019-03-13
      • 2018-11-26
      • 2018-10-22
      • 2022-11-25
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      相关资源
      最近更新 更多