HQL:一个集合的元素是否在另一个集合中?

11

我想检查集合(u.organisations)中是否至少存在一个元素也在另一个集合(? = excludedOrganisations)中:

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

嘿,你在这方面有进展了吗? - octav
我的解决方法是使用for循环,这在相对较少的元素情况下是可能的。 - deamon
尝试传入仅包含组织ID的列表,而不是组织列表。我尝试过类似的方法,它可以工作。 - octav
2个回答

0

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

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

它不起作用,可能是因为每个用户组可以有多个用户。 - deamon
我也尝试过在子查询中使用 select 1 from UserGroup g where u in elements(g.users) and g not in (?),但没有成功。 - deamon

0

这是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无法转换为java.lang.Long。 - deamon
你将ID集合作为参数传递给查询,是吗?不是机构集合。 - octav
这是一组组织对象。 - deamon
尝试仅传递其ID列表。 - octav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接