简体   繁体   English

带有SELECT子句中的子查询的JPQL /休眠查询

[英]JPQL/Hibernate query with Subquery in SELECT clause

I have a set of JPA entity classes as below (simplified): 我有一组JPA实体类,如下所示(简化):

@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. 每个用户可以通过user_region表与0个或更多区域相关联。

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. 使用JPQL,我试图创建一个查询,该查询将为我提供Object []列表,其中第一项是区域,第二项是分配给该区域的用户数。

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. 查看相关问题的答案,似乎SELECT部分​​中的子选择不起作用,因为它们仅在WHERE和HAVING部分中被允许,但这不会引发任何语法异常,它的计数结果为零,所以我对此不确定。

Can anyone tell me how to rework the query to work with multiple regions? 谁能告诉我如何重新处理查询以在多个区域工作?

Using JPA 2.0 with Hibernate 4.2 结合使用JPA 2.0和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. 这对于没有用户的区域可能不起作用,如果不需要用户,则可以使用右联接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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