title: JPA 2 Hibernate Group BY and Count * with other columns
body: <p>I am stuck in finding a way to do the Group BY and Count * with other columns using JPA 2 Hibernate EntityManager + CriteriaBuilder apis. What is the best way to do this. </p>
  
  <p>My sql query will be as simple as </p>
  
  <pre><code>select type, count(*) from test group by type
  </code></pre>
  
  <p>I have Test Entity created with exact mapping.</p>
  
  <p>But finally I am needed the result with an extra field for count. I have seen example of using hibernate sessions and using projections for the same. But since I am using JPA2 CriteriaBuilder I couldn't able to use it.
  <a href="https://stackoverflow.com/questions/23044565/count-with-other-fields-in-group-by-with-hibernate">count with other fields in group by with hibernate</a></p>
  
  <p>I am sure there will be some simple and more elegant way to do this. Let me know if anyone knows it.</p>
  
  <p><strong>Edit 1</strong></p>
  
  <p>As of now I am able to do to an extend without using criteria builder</p>
  
  <pre><code>List&lt;Object[]&gt; results = em
                  .createQuery("SELECT m.type AS name, COUNT(m) AS total FROM Test AS m GROUP BY m.type ORDER BY m.type ASC").getResultList();
  
          for (Object[] result : results) {
              String name = String.valueOf( result[0]);
              int count = ((Number) result[1]).intValue();
  
              logger.info(name + "   " + count);
          }
  </code></pre>
  
  <p>But I need to do the same using CriteriaBuilder and i may need to dynamically inject where clauses based on my filter arguments.</p>