如何使用JPA CriteriaQuery计算自定义实体的结果

时间:2015-10-04 15:46:30

标签: jpa criteria-api jpa-2.1

我正在使用JPA2.1条件API,其中我使用条件构建器构造创建了一个结果对象。

考虑以下示例代码。

<div id="table-wrapper">
  <div id="table-scroll">
    <table class="table" border="1" border-spacing="2" padding="2" >
      <tr class="row">
        <td>
          <font face="Arial, Helvetica, sans-serif">Staff ID</font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif">Name</font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif">Position</font>
        </td>
      </tr>

      <?php
        $i = 0;
        while ($i < $num) {
          $f1 = mysql_result($result, $i, "ID");
          $f2 = mysql_result($result, $i, "Name");
          $f3 = mysql_result($result, $i, "Position");
      ?>

      <script>
        function myFunction(x) {
          alert("Row index is: " + x.rowIndex);
          //i can get the row number using this
        }
      </script>

      <tr onclick="myFunction(this)">
        <td>
          <font face="Arial, Helvetica, sans-serif"><?php echo $f1;  ?></font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font>
        </td>
        <td>
          <font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font>
        </td>
      </tr>

      <?php
          $i++;
        }  
      ?>
    </table>
  </div>
</div>

以下是我选择的主线。

CriteriaBuilder cb;//Assume cb is obtained here 
CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class
Root<Student> root = cq.from(Student.class);
Join<Student, XTable> join1 = root.join("xtable", JoinType.INNER);
Join<Student, YTable> join1 = root.join("ytable", JoinType.INNER); 

现在,我想对这个构造cq.select(cb.construct(Report.class, root.get("name"), join1.get("address_type"), join2.get("country"))); 进行统计。

我试过这样算。

Report

如何计算?

1 个答案:

答案 0 :(得分:2)

我认为它看起来像这样:

您的代码:

CriteriaBuilder cb;//Assume cb is obtained here 
CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class
Root<Student> root = cq.from(Student.class);
Join<Student, XTable> join1 = root.join("xtable", JoinType.INNER);
Join<Student, YTable> join1 = root.join("ytable", JoinType.INNER); 
countItemsByCriteria(entityManagerReference, cq, cb);


private <T> Long countItemsByCriteria(EntityManager em, CriteriaQuery<T> cqEntity, CriteriaBuilder cb) {
    CriteriaBuilder builder = cb;
    CriteriaQuery<Long> cqCount = builder.createQuery(Long.class);
    Root<?> entityRoot = cqCount.from(cqEntity.getResultType());
    cqCount.select(builder.count(entityRoot));
    cqCount.where(cqEntity.getRestriction());
    return em.createQuery(cqCount).getSingleResult();
}

正如本文所述:JPA + Hibernate count(*) using CriteriaBuilder - with generatedAlias