问题描述
我正在尝试实现以下便捷方法:
I am trying to implement the following convenience method:
/**
* 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 中,这是由
In Hibernate, this is done by
criteria.setProjection(Projections.rowCount());
JPA 中与上面的等价物是什么?我找到了许多简单的计数示例,但没有一个使用 CriteriaQuery 应确定其行数.
What is the equivalent to the above in JPA? I found numerous simple count examples, but none of them made use of a CriteriaQuery whose row count should be determined.
不幸的是,我发现@Pascal 的答案不正确.这个问题很微妙,只有在你使用连接时才会出现:
I unfortunately found out that @Pascal's answer is not the correct one. The problem is very subtle and only shows up when you use joins:
// 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)
时,它会因以下异常而死亡:
When calling findCountByCriteria(query)
, it dies with the following exception:
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
方法吗?
Is there any other way to provide such a CountByCriteria
method?
推荐答案
我写了一个实用类,JDAL JpaUtils去做:
I wrote a utility class, JDAL JpaUtils to do it:
- 计数结果:
Long count = JpaUtils.count(em,criteriaQuery);
- copy CriteriaQueries:
JpaUtils.copyCriteria(em,criteriaQueryFrom,criteriaQueryTo);
- 获取计数条件:
CriteriaQuerycountCriteria = JpaUtils.countCriteria(em,criteria)
等等...
如果你对源代码感兴趣,请看JpaUtils.java
If you are interested in the source code, see JpaUtils.java
这篇关于JPA 2.0:计数任意 CriteriaQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!