简体   繁体   中英

JPQL - how to select all entities not referred to by any row from other entity set

I have entity Parent and Child with unilateral relation Child n -> 1 Parent . In other words Parent does not know about its children.

How to write an JPQL query which would select all instances of Parent which are not referred to by a particular subset of Child which meet certain predicate?

Example: select all parents which are not referred to by children who are younger than 8 years

You can try a LEFT OUTER JOIN on the parent/child relationship, eg:

SELECT c, p.name FROM Country c LEFT OUTER JOIN c.capital p

If the nulls are a problem, you can get rid of them by adding something like:

... WHERE p.id IS NOT NULL

For further detailed explanation, see this guide: http://www.objectdb.com/java/jpa/query/jpql/from#LEFT_OUTER_JOIN_

If the parent does not know about the children, then you can achieve similar results by using a subquery to filter parent, eg:

SELECT e.parent_id
    FROM ParentEntity e
    WHERE e.parent_id NOT IN (
    SELECT c.parent_id FROM ChildEntity c) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM