我有新问题。我创建了一些代码,从客户端请求中生成谓词。这是初始化部分:Jpa标准计数
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
也许我应该说,这根生成动态加入:
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)'
你用什么方式使用parseField? – Amalgovinus