我有新問題。我創建了一些代碼,從客戶端請求中生成謂詞。這是初始化部分: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