Jpa 条件计数

Jpa criteria count

我有新问题。我创建了一些代码,根据客户请求生成谓词。这是初始化部分:

 criteriaBuilder = entityManager.getCriteriaBuilder();
 criteriaQuery = criteriaBuilder.createQuery(classEntity);
 root = criteriaQuery.from(classEntity);

当我想要获取列表实体时,效果很好:

criteriaQuery.select(root).where(predicate);
entityManager.createQuery(criteriaQuery).getResultList();

但是当我想获取计数实体时:

CriteriaQuery<Long> cq = criteriaBuilder.createQuery(Long.class);
cq.select(criteriaBuilder.count(root)).where(predicate);
System.err.println("eee : " +entityManager.createQuery(cq).getSingleResult());

异常掉落

java.lang.IllegalArgumentException: Error occurred validating the Criteria Caused by: java.lang.IllegalStateException: No criteria query roots were specified

也许我应该说,root 生成动态连接:

private Path parseField(String field) {
    Path path = null;

    if (field.contains(".")) {

        String [] split = field.split("\.");
        Join join = root.join(split[0],JoinType.INNER);

        for (int i =1; i < split.length-1; i++) {
            join = join.join(split[i],JoinType.INNER);
        }

        path = join.get(split[split.length-1]);

    } else {
        path = root.get(field);
    }
    return path;
}

如果我更换

cq.select(criteriaBuilder.count(root)).where(previousPredicate);

cq.select(criteriaBuilder.count(cq.from(classEntity))).where(previousPredicate);

我将失败并出现异常

 org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.(someFieldName)' 

对我来说一切正常:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
Root<A> r = q.from(A.class);
MapJoin<A, String, String> m = r.joinMap("metadata");
q.select(cb.count(r)).where(cb.equal(m.key(), "A"));
Long rs = em.createQuery(q).getSingleResult();

所以,如果没有 MCVE,很难看出你做错了什么。