我有新问题。我从客户端请求创建了一些生成谓词的代码。这是初始化部分:
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)'
答案 0 :(得分:2)
一切都适合我:
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,很难看出你做错了什么。