【问题标题】:Hibernate JPA CriteriaQuery with count and where predicateHibernate JPA CriteriaQuery with count 和 where 谓词
【发布时间】:2020-08-24 12:26:09
【问题描述】:

我正在尝试使用 CriteriaQuery 在 JPA/Hibernate 中复制此查询的结果。

select count(*) from tbl_survey where CREATED_DATE > to_date('2020-04-01', 'yyyy-mm-dd') 

daysBack 值作为参数传入。

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, daysBack);
    Date daysAgo = cal.getTime();
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Long> cq = cb.createQuery(Long.class);
        Root<Survey> root = cq.from(Survey.class);
        Path<Date> dateCreated = root.<Date>get("createdDate");
        Predicate datePredicate = cb.greaterThanOrEqualTo(dateCreated, daysAgo);
        cq.where(datePredicate);
        cq.select(cb.count(cq.from(Survey.class)));

        long count = entityManager.createQuery(cq).getSingleResult();
        JSONObject resultJson = new JSONObject();
        resultJson.put(SURVEY_COUNT, count);

        logger.info("Count for Survey table is: {}", count);
        return new ResponseEntity<>(resultJson.toString(), HttpStatus.OK);
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage(), e);
        return new ResponseEntity(e.getLocalizedMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

日志输出为: 调查表的计数是:36

但是,表中只有 6 行表明正在生成某种自联接或叉积来创建 36 的输出。我应该采取哪些不同的措施来获得正确的计数?

【问题讨论】:

    标签: hibernate spring-data-jpa jpa-2.0


    【解决方案1】:

    在您使用新 root 的这一行发生自连接

    cq.select(cb.count(cq.from(Survey.class)));
    

    root 用于 where 条件和 count 查询不同导致自加入。计数查询也使用相同的根

    cq.select(cb.count(root)); 
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2012-08-28
      • 2015-12-16
      • 1970-01-01
      • 2013-10-11
      • 2012-01-05
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      相关资源
      最近更新 更多