title: JPA 2 Criteria API, children count criteria
body: <p>I am trying to implement something like:  </p>
  
  <pre><code>SELECT c.*, asCount.assetCount
  FROM Company c
  LEFT JOIN (
      SELECT company_id, COUNT(*) as assetCount 
      FROM Asset 
      GROUP BY company_id) asCount
  ON c.id = asCount.company_id
  </code></pre>
  
  <p><strong>Question:</strong> How could I implement this with JPA 2 Criteria?  </p>
  
  <p>I am able to get the asCount results separately, but do not know how to join it to the Company  </p>
  
  <pre><code>CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery&lt;Tuple&gt; cq = builder.createTupleQuery();
  Root&lt;Asset&gt; asset = cq.from(Asset.class);
  cq.multiselect(asset.&lt;Company&gt;get("company").&lt;Long&gt;get("id").alias("id"), builder.count(asset).alias("assetCount"));
  cq.groupBy( asset.&lt;Company&gt;get("company").&lt;Long&gt;get("id") );
  
  Query query = em.createQuery(cq);
  List&lt;Tuple&gt; results = query.getResultList();
  </code></pre>
  
  <p>Thanks in advance.  </p>
  
  <p>PS<br>
  1. There's a similar thread asking children count using Hibernate API:
  <a href="https://stackoverflow.com/questions/4255382/hibernate-children-count-criteria">Hibernate children count criteria</a><br>
  2. Another useful thread describing the topic: <a href="https://stackoverflow.com/questions/14425674/jpa-criteriabuilder-sort-by-the-number-of-associated-entities-in-a-one-to-many">JPA CriteriaBuilder - sort by the number of associated entities in a one-to-many relationship</a></p>