title: Criteria API count from grouped count
body: <p>I have a problem with Criteria API (JPA 2.0). I want to write code which returns the same result as query (select count from (select count from ... group by ...)):</p>
  
  <pre><code>SELECT COUNT(*) FROM (
      SELECT COUNT(*) FROM a
      LEFT JOIN p ON a.id = p.a_id
      LEFT JOIN s ON a.id = s.a_id
      WHERE ... GROUP BY s.r_id
  )
  </code></pre>
  
  <p>I wrote something like this:</p>
  
  <pre><code>CriteriaBuilder builder = slave.getCriteriaBuilder();
  CriteriaQuery&lt;Long&gt; query = builder.createQuery(Long.class);
  Subquery&lt;Long&gt; subquery = query.subquery(Long.class);       
  Root&lt;A&gt; entity = subquery.from(A.class);
  Join&lt;A, P&gt; pJoin = entity.join("p", JoinType.LEFT);
  Join&lt;A, S&gt; sJoin = entity.join("s", JoinType.LEFT);
  subquery.select(builder.count(entity));
  subquery.where(/*where predicate*/);
  subquery.groupBy(sJoin.get("r"));
  query.select(builder.count(subquery));
  Long result = slave.createQuery(query).getSingleResult();
  </code></pre>
  
  <p>But I get the exception: </p>
  
  <blockquote>
    <p>java.lang.IllegalStateException: No criteria query roots were specified</p>
  </blockquote>
  
  <p>What am I doing wrong here?</p>