【问题标题】:JPA/Hibernate select element not in collectionJPA/Hibernate 选择元素不在集合中
【发布时间】:2012-05-15 23:15:41
【问题描述】:

如果我有两个实体类GroupPerson,其中GroupPerson之间存在一对多的关系(即一个人最多可以属于一个组,一个组可以有很多人),我可以使用什么 jpql/hql 查询来选择所有不在Groups 中的Persons?

类似于select p from Group g inner join g.people p 的反面...

【问题讨论】:

    标签: hibernate jpa jpql


    【解决方案1】:

    如果你想让所有不在给定组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 很好。编辑问题以反映这一点。
    • 组与人之间存在 1:n 的关系。然后在数据库中,表 person 将组 id 作为组的外键。通过正确的映射,可以在 person 实例中访问此外键 - 可以使用多对一关系,然后使用 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”列。
    【解决方案2】:

    这行得通:

    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 了解哪个更有效,但由于这两个“有效”,将问题标记为已回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多