我正在尝试实现以下便捷方法:
/**
* Counts the number of results of a search.
* @param criteria The criteria for the query.
* @return The number of results of the query.
*/
public int findCountByCriteria(CriteriaQuery<?> criteria);
在 Hibernate 中,这是由
criteria.setProjection(Projections.rowCount());
JPA中与上述等效的是什么?我发现了许多简单的计数示例,但没有一个使用应该确定行数的 CriteriaQuery。
编辑:
不幸的是,我发现@Pascal 的答案不是正确的。这个问题非常微妙,只有在您使用连接时才会出现:
// Same query, but readable:
// SELECT *
// FROM Brain b
// WHERE b.iq = 170
CriteriaQuery<Person> query = cb.createQuery(Person.class);
Root<Person> root = query.from(Person.class);
Join<Object, Object> brainJoin = root.join("brain");
Predicate iqPredicate = cb.equal(brainJoin.<Integer>get("iq"), 170);
query.select(root).where(iqPredicate);
调用时findCountByCriteria(query)
,它会因以下异常而死:
org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.iq' [select count(generatedAlias0) from xxx.tests.person.dom.Person as generatedAlias0 where generatedAlias1.iq=170]
有没有其他方法可以提供这种CountByCriteria
方法?