次の便利なメソッドを実装しようとしています。
/**
* 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
か?