Search code examples
javajpaspring-data-jpaspring-datajpql

JPA Query for "Set does NOT contain a certain item"


Let's say we have a class Person which contains Set<Book> books.

To find all the persons with book "Effective Java", you could write:

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

Now, how can I turn this query on it's head, and find all the Person without this book?

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

Solution

  • You could take advantage of the NOT EXISTS keyword:

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