简体   繁体   中英

JPQL/Hibernate query with Subquery in SELECT clause

I have a set of JPA entity classes as below (simplified):

@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<Region> regions;
}

Each user can be associated with 0 or more regions, via the user_region table.

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.

Doing it for a single region is easy:

"select count(u) from " + User.class.getName() + " u " +
            "where :region member of u.regions"

This works fine.

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:

"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";

but this results in a zero count for each region (which isn't right as the single select returns nonzero results).

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.

Can anyone tell me how to rework the query to work with multiple regions?

Using JPA 2.0 with Hibernate 4.2

You could achieve this using:

 select r, count(u) from " + User.class.getName() + " u inner join u.regions r where r in :regionList group by r

This may not work for regions with no users, you could use right join in case regions with no users are needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM