簡體   English   中英

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 ,很難看出你做錯了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM