我正在使用hibernate和JPA条件API并尝试创建一个可重用的实用程序方法来确定查询将返回多少行。
目前我有这个:
Long countResults(CriteriaQuery cq, String alias){
CriteriaBuilder cb = em().getCriteriaBuilder();
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
Root ent = countQuery.from(cq.getResultType());
ent.alias(alias);
countQuery.select(cb.count(ent));
Predicate restriction = cq.getRestriction();
if(restriction != null){
countQuery.where(restriction);
}
return em().createQuery(countQuery).getSingleResult();
}
我使用的是这样的:
CriteriaBuilder cb = em().getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(modelClass());
root.alias("ct");
cq.select(root);
TypedQuery<User> query = em().createQuery(cq);
long count = countResults(cq, "ct");
这很好用。 但是,当我使用更复杂的查询,如
Join<UserThing, Thing> j = root.join(User_.things).join(UserThing_.thing);
cq.where(somePredicate);
我对countResults()
的电话会产生org.hibernate.hql.internal.ast.InvalidPathException: Invalid path: 'myAlias.name'
,<AST>:0:0: unexpected end of subtree
,left-hand operand of a binary operator was null
我猜这与连接有关,而且我需要别名,但到目前为止我还没有取得任何成功。
帮助?
答案 0 :(得分:0)
我遇到了同样的问题,我解决了:
CriteriaQuery<Long> countCriteria = cb.createQuery(Long.class);
Root<EntityA> countRoot = countCriteria.from(cq.getResultType());
Set<Join<EntityA, ?>> joins = originalEntityRoot.getJoins();
for (Join<EntityA, ?> join : joins) {
countRoot.join(join.getAttribute().getName());
}
countCriteria.select(cb.count(countRoot));
if(finalPredicate != null)
countCriteria.where(finalPredicate);
TypedQuery<Long> queryCount = entityManager.createQuery(countCriteria);
Long count = queryCount.getSingleResult();
其中
originalEntityRoot是我使用where子句进行查询的主根。