Note that there are some explanatory texts on larger screens.

plurals
  1. POJPA 2.0: count for arbitrary CriteriaQuery?
    text
    copied!<p>I am trying to implement the following convenience method:</p> <pre><code>/** * 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&lt;?&gt; criteria); </code></pre> <p>In Hibernate, this is done by </p> <pre><code>criteria.setProjection(Projections.rowCount()); </code></pre> <p>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.</p> <p><strong>EDIT:</strong></p> <p>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:</p> <pre><code>// Same query, but readable: // SELECT * // FROM Brain b // WHERE b.iq = 170 CriteriaQuery&lt;Person&gt; query = cb.createQuery(Person.class); Root&lt;Person&gt; root = query.from(Person.class); Join&lt;Object, Object&gt; brainJoin = root.join("brain"); Predicate iqPredicate = cb.equal(brainJoin.&lt;Integer&gt;get("iq"), 170); query.select(root).where(iqPredicate); </code></pre> <p>When calling <code>findCountByCriteria(query)</code>, it dies with the following exception:</p> <pre><code>org.hibernate.hql.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.iq' [select count(generatedAlias0) from xxx.tests.person.dom.Person as generatedAlias0 where generatedAlias1.iq=170] </code></pre> <p>Is there any other way to provide such a <code>CountByCriteria</code> method?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload