ORM – JPA 2.0: count any criteriaquery?

I try to achieve the following convenient methods:

/**
 * 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);

In Hibernate, this is done

criteria.setProjection(Projections.rowCount());

What is the equivalent of the above in JPA? I found many simple counting examples, but none used criteriaquery, and the number of rows should be determined

Edit:

Unfortunately, I found that @ Pascal's answer was incorrect The problem is very subtle and only occurs when you use a connection:

// 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);

When findcountbycriteria (query) is called, it will crash with the following exceptions:

org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.iq' [select count(generatedAlias0) from xxx.tests.person.dom.Person as generatedAlias0 where generatedAlias1.iq=170]

Is there any other way to provide such countbycriteria method?

Solution

I wrote a practical class, JDAL jpautils:

> count results:Long count = JpaUtils. count(em,criteriaQuery); > Copy criteriaqueries: jpautils copyCriteria(em,criteriaQueryFrom,criteriaQueryTo); > Get counting condition: criteriaquery < long > countcriteria = jpautils countCriteria(em,criteria)

Wait

If you are interested in the source code, see jpautils java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>