【发布时间】:2012-05-15 23:15:41
【问题描述】:
如果我有两个实体类Group和Person,其中Group和Person之间存在一对多的关系(即一个人最多可以属于一个组,一个组可以有很多人),我可以使用什么 jpql/hql 查询来选择所有不在Groups 中的Persons?
类似于select p from Group g inner join g.people p 的反面...
【问题讨论】:
如果我有两个实体类Group和Person,其中Group和Person之间存在一对多的关系(即一个人最多可以属于一个组,一个组可以有很多人),我可以使用什么 jpql/hql 查询来选择所有不在Groups 中的Persons?
类似于select p from Group g inner join g.people p 的反面...
【问题讨论】:
如果你想让所有不在给定组g中的人,应该像
from Person p where p.group.id != :gid;
然后将 gid 设置为给定组的 id。
如果你想让所有的人根本不属于任何组
from Person p where p.group.id is null;
如果你想让所有人都不在任何组中,但 Person 中的外键可能有一个不为空但不属于现有组的组 id(例如,如果组是删除而不删除其中的人,也没有将他们移动到不同的组)
from Person p where not exist (select 1 from Group g where g.id = p.group.id);
P。 S. 我的陈述是针对 HQL 的,但针对 JPQL 应该或多或少相同。
【讨论】:
Person 没有对 Group 的引用,只是反过来。不过,HQL 很好。编辑问题以反映这一点。
p.group.id' as I did in the examples, or directly as a literal, then use sth. like p.groupId. If the foreign key is not mapped yet, then I recommend to map it - that is much faster than any not exists` 或 not in 构造。
Person 中的“组ID”列。
这行得通:
select p from Person p where p not in (select pg from Group g inner join g.persons pg)
也许:
select p from Person p where not exists (select 1 from Group g where p member of g.persons)
效率更高?
无论如何...欢迎 cmets 了解哪个更有效,但由于这两个“有效”,将问题标记为已回答。
【讨论】: