【问题标题】:HQL: Is an element of one collection in another collection?HQL:一个集合的元素是否在另一个集合中?
【发布时间】:2011-05-23 00:31:46
【问题描述】:

我想检查一个集合 (u.organisations) 的至少一个元素是否包含在另一个集合中 (? = excludeOrganisations):

select distinct u from SystemUser u
join u.userGroups g 
join u.organisations o
where 3 in elements(g.permissions) and
EACH_ELEMENT_OF(o) not in (?)

如何用 HQL 表达EACH_ELEMENT_OF

我的最后一次试验是:

select distinct u from SystemUser u 
join u.userGroups g 
where 3 in elements(g.permissions) and 
not exists (
    select org from Organisation org 
    where org in elements(u.organisations)
    and org not in (?)
)

但我得到了例外:

IllegalArgumentException occurred calling getter of Organisation.id

【问题讨论】:

  • 嘿,你在这方面有什么进展吗?
  • 我的解决方法是使用 for 循环,这可以通过相对较少的元素实现。
  • 尝试传入一个组织列表,而不是一个仅包含其 ID 的列表。我已经尝试过类似的方法,并且成功了。

标签: hibernate collections hql


【解决方案1】:

我猜你需要一个子查询在 SQL 中表达它,因此在 HQL 中也需要子查询:

select u from SystemUser u 
where not exists (
    select 1 from UserGroup g where g.user = u and g not in (?)
)

【讨论】:

  • 不行,可能是因为每个UserGroup可以有多个用户。
  • 我也在子选择中尝试了select 1 from UserGroup g where u in elements(g.users) and g not in (?),但没有成功。
【解决方案2】:

这是来自 Hibernate 文档的经典示例:

from Cat as cat
left join cat.kittens as kitten
    with kitten.bodyWeight > 10.0

在你的情况下,这将是:

select distinct u from SystemUser u 
join u.userGroups g
join u.organisations o 
where 3 in elements(g.permissions) and 
 o.id not in (?)

我假设组织实体有一个 id 字段,您可以传入 id 列表。

【讨论】:

  • 组织有一个 id 字段。但是当我尝试执行您的查询时,我得到:org.hibernate.collection.PersistentSet cannot be cast to java.lang.Long
  • 您将作为参数传递给查询的 id 集,对吗?不是组织的集合..
  • 这是一组组织对象。
  • 尝试只传入他们的 id 列表。
猜你喜欢
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 2021-12-08
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多