title: JPA criteria return a page and total
body: <p>for a paged data (paginated) I need to return the total number of records matching my criteria and the results first page. this is useful to display information for the users and calculate the total number of pages to expect (on the client).</p>
  
  <p>at the moment I run the same query twice, once for the total count and once for the actual records. I hope there is a more efficient way.</p>
  
  <p>can these two queries be combined to one call to the database?</p>
  
  <p>the count:</p>
  
  <pre><code>    CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery&lt;Long&gt; cq = cb.createQuery(Long.class);
      Root&lt;VersionJpa&gt; r = cq.from(VersionJpa.class);
      Predicate p = cb.conjunction();
      p = // some filtering code define by caller
      cq.where(p);
      cq.select(cb.count(r));
      TypedQuery&lt;Long&gt; tq = em.createQuery(cq);
      return tq.getSingleResult().intValue();
  </code></pre>
  
  <p>the page:</p>
  
  <pre><code>    CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery&lt;VersionJpa&gt; cq = cb.createQuery(VersionJpa.class);
      Root&lt;VersionJpa&gt; root = cq.from(VersionJpa.class);
      Predicate p = cb.conjunction();
      p = // same filtering code as in the count above
      cq.where(p);
      TypedQuery&lt;VersionJpa&gt; tq = em.createQuery(cq);
      // paginatong
      tq.setFirstResults(first); // from caller
      tq.setMaxResults(max);     // from caller
      return tq.getResultList();
  </code></pre>