带有计数和谓词的Hibernate JPA CriteriaQuery

问题描述 投票:1回答:1

我正在尝试使用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个回答
0
投票

此行使用新的根目录时会发生自动联接

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

用于条件和计数查询的地方所使用的根是不同的,从而导致自连接。也使用相同的根进行计数查询]

cq.select(cb.count(root)); 
© www.soinside.com 2019 - 2024. All rights reserved.