title: How to count the number of rows of a JPA 2 CriteriaQuery in a generic JPA DAO?
body: <p>I'm new in JPA and want to implement a generic JPA DAO and need to find the number of rows of a query result set to implement pagination. After searching the web, I can't find a practical way to do that. Here is the code suggested in many articles:</p>
  
  <pre><code>public &lt;T&gt; Long findCountByCriteria(CriteriaQuery&lt;?&gt; criteria) {
      CriteriaBuilder builder = em.getCriteriaBuilder();
  
      CriteriaQuery&lt;Long&gt; countCriteria = builder.createQuery(Long.class);
      Root&lt;?&gt; entityRoot = countCriteria.from(criteria.getResultType());
      countCriteria.select(builder.count(entityRoot));
      countCriteria.where(criteria.getRestriction());
  
      return em.createQuery(countCriteria).getSingleResult();
  }
  </code></pre>
  
  <p>However, that code doesn't work when using <code>join</code>. Is there any way to count the rows of a query result set using the JPA Criteria API?</p>
  
  <p>UPDATE :
  here is the code that create CriteriaQuery :</p>
  
  <pre><code>    CriteriaQuery&lt;T&gt; queryDefinition = criteriaBuilder.createQuery(this.entityClass);
      Root&lt;T&gt; root = queryDefinition.from(this.entityClass);
  </code></pre>
  
  <p>and some joins may be added to the root until the query have been executed:</p>
  
  <pre><code>public Predicate addPredicate(Root&lt;T&gt; root) {
                  Predicate predicate = getEntityManager().getCriteriaBuilder().ge(root.join(Entity_.someList).get("id"), 13);
                  return predicate;
  }
  </code></pre>
  
  <p>and the generated exception is like :</p>
  
  <blockquote>
    <p>org.hibernate.hql.ast.QuerySyntaxException: Invalid path:
    'generatedAlias1.id' [select count(generatedAlias0) from entity.Entity
    as generatedAlias0 where ( generatedAlias0.id>=13L ) and (
    (generatedAlias1.id&lt;=34L ) )]</p>
  </blockquote>
  
  <p>which generatedAlias1 should be on Entity and generatedAlias0 should be on the association that I joined on that.
  Note that I implement Join properly because when I execute query without count query it executes without error and the Join works properly but when I try to execute count query it throws exception. </p>