title: JPQL/Hibernate query with Subquery in SELECT clause
body: <p>I have a set of JPA entity classes as below (simplified):</p>
  
  <pre><code>@Entity(name="region")
  public class Region {
  
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    protected Long id;
  }
  
  @Entity(name="user")
  public class User {
  
    @OneToMany(fetch = FetchType.EAGER)
    @JoinTable
    (
        name="user_region",
        joinColumns={ @JoinColumn(name="user_id", referencedColumnName="id") },
        inverseJoinColumns={ @JoinColumn(name="region_id", referencedColumnName="id", unique=true) }
    )
    protected Set&lt;Region&gt; regions;
  }
  </code></pre>
  
  <p>Each user can be associated with 0 or more regions, via the user_region table.</p>
  
  <p>Using JPQL, I am trying to create a query that will give me a list of Object[], where the first item is the region, and the second is a count of users assigned to that region.</p>
  
  <p>Doing it for a single region is easy:</p>
  
  <pre><code>"select count(u) from " + User.class.getName() + " u " +
              "where :region member of u.regions"
  </code></pre>
  
  <p>This works fine.</p>
  
  <p>But I was hoping to not have to batter the database with a call for each region, so wanted to get them all together.  I have tried:</p>
  
  <pre><code>"select r, (" +
              "  select count(u) from " + User.class.getName() + " u " +
              "  where r member of u.regions " +
              ") from " + Region.class.getName() + " r " +
              "where r in :regionList";
  </code></pre>
  
  <p>but this results in a zero count for each region (which isn't right as the single select returns nonzero results).  </p>
  
  <p>Looking at answers to related questions, it appears subselects in the SELECT part shouldnt work as they are only allowed in the WHERE and HAVING parts, but this doesn't throw any syntax exceptions, it just has a zero result for the count, so I am unsure about this.</p>
  
  <p>Can anyone tell me how to rework the query to work with multiple regions?</p>
  
  <p>Using JPA 2.0 with Hibernate 4.2</p>