【问题标题】:JPA Query for "Set does NOT contain a certain item"“集合不包含某个项目”的 JPA 查询
【发布时间】:2019-02-01 13:05:55
【问题描述】:

假设我们有一个类Person,其中包含Set<Book> books

要找到所有书“Effective Java”的人,你可以这样写:

select p from Person p left outer join fetch p.books as b where b.name='Effective Java'

现在,我怎样才能完全颠覆这个查询,找到所有Person没有这本书?

select p from Person p "where p.books does not contain book b where b.name='Effective Java'"

【问题讨论】:

    标签: java jpa spring-data-jpa spring-data jpql


    【解决方案1】:

    您可以利用 NOT EXISTS 关键字:

    select p 
    from Person p
    where not exists (
       select b from p.books b where b.name = 'Effective Java'
    )
    

    【讨论】:

    • 是的,我也是!将这种能力推回数据库要好得多,而不是 persons.getBooks().stream.filter(....) :) 非常感谢!周末愉快
    【解决方案2】:

    或者怎么样

     select p from Person p join p.books b where b.name <> 'Effective Java'
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 2021-09-02
      • 1970-01-01
      相关资源
      最近更新 更多