【问题标题】:JPQL/Hibernate query with Subquery in SELECT clause在 SELECT 子句中使用子查询的 JPQL/Hibernate 查询
【发布时间】:2014-08-01 18:00:01
【问题描述】:

我有一组 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;
}

每个用户可以通过 user_region 表与 0 个或多个区域相关联。

使用 JPQL,我正在尝试创建一个查询,该查询将为我提供一个 Object[] 列表,其中第一项是区域,第二项是分配给该区域的用户数。

为单个区域做这件事很容易:

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

这很好用。

但我希望不必通过调用每个区域来破坏数据库,因此希望将它们放在一起。我试过了:

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

但这会导致每个区域的计数为零(这是不正确的,因为单个选择返回非零结果)。

查看相关问题的答案,似乎 SELECT 部分中的子选择不应该工作,因为它们只允许在 WHERE 和 HAVING 部分中使用,但这不会引发任何语法异常,它只是计数结果为零,所以我不确定。

谁能告诉我如何修改查询以处理多个区域?

将 JPA 2.0 与 Hibernate 4.2 结合使用

【问题讨论】:

  • 有没有办法从Region 导航到它的用户?如果是这样的话,像r, count(r.users) 这样的东西可能会起作用(或者可能是r, size(r.users),我现在无法查找)。如果实体看起来像上面那样,即您没有将它们剥离,那么您可以考虑将一组用户添加到 Region
  • 不,不幸的是,地区不知道用户。这只是用户 区域
  • 你可以试试 --> select r, count(u) from " + User.class.getName() + " u inner join u.regions r where r in :regionList group by r跨度>
  • 谢谢Gayathri!这工作得非常出色。如果可以的话,我会用勾号标记。
  • 很高兴它成功了!你现在可以标记它! :-)

标签: java hibernate jpa jpql


【解决方案1】:

您可以使用:

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

这可能不适用于没有用户的区域,如果需要没有用户的区域,您可以使用 right join。

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 2014-02-23
    • 2018-09-07
    • 2021-11-16
    • 2016-09-24
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多