title: JPA Criteria: Obtain total count just before full result with all columns; reuse Where clause
body: <p>In <strong>JPA Criteria</strong> I have a complex query which works. It involves many Joins and a complex Where clause. But right before I run it for the full selection, I need to get a quick <code>COUNT</code> of the full resultset.</p>
  <p>I tried to reuse my <code>where</code> clause and all my Joins and select from my top element, <code>nvRoot</code>, using <code>cb.count</code>. But I got the error <code>Caused by: java.lang.IllegalStateException: No criteria query roots were specified</code>.</p>
  <pre><code>     CriteriaBuilder cb = entityManager.getCriteriaBuilder();
       CriteriaQuery&lt;Result&gt; criteriaQuery = cb.createQuery(Result.class);
       Root&lt;NvisionTrainee&gt; nvRoot = criteriaQuery.from(Nv.class);
       Join&lt;Object,Object&gt; plans = nvRoot.join(&quot;plans&quot;, JoinType.LEFT);
       // etc., other Joins
  
       Predicate where = cb.conjunction();
       // Complex Where clause built...
       criteriaQuery.where(where);
  
       // --- HERE I NEED TO RUN A QUICK COUNT QUERY, with all Joins/Where as built
       // --- BUT THE BELOW DOESN'T WORK: 
       // --- Caused by: java.lang.IllegalStateException: No criteria query roots were specified
       CriteriaQuery&lt;Long&gt; cqCount = cb.createQuery(Long.class);
       cqCount.select(cb.count(nvRoot));     
       cqCount.distinct(true);
       cqCount.where(where);
       Long totalCount = entityManager.createQuery(cqCount).getSingleResult();
  
       // --- THIS FULL QUERY WORKS (THE REMAINDER), IT GETS ME MY FULL SELECTION
       CompoundSelection&lt;Result&gt; selectionFull = cb.construct(
                                     Result.class,
                                     nvRoot.get(&quot;firstName&quot;),
                                     // etc. - many columns
                                     );
       criteriaQuery.select(selectionFull);
       criteriaQuery.distinct(true);
       TypedQuery&lt;Result&gt; query = entityManager.createQuery(criteriaQuery);
       List&lt;Result&gt; results = query.getResultList();
  </code></pre>
  <p>Per the comment below, I tried adding <code>cqCount.from(Nv.class)</code> in the code, but that gave me:</p>
  <p><code>Invalid path: 'generatedAlias2.id'</code></p>