【发布时间】:2013-03-10 11:48:33
【问题描述】:
我正在尝试编写一个 JPQL 查询来返回实体,其中该实体的所有子实体都具有一组值中的属性。它类似于以下问题,但有多个可能的值:
Hibernate query - How to select those parents that have ALL the children matching a value?
这是根据上述问题改编的一个实际示例...
我想选择那些所有孩子都是金发或红发的父亲。如果只有一个是黑发的,则不会选择父亲。
我已尝试对上述问题的答案进行各种修改,例如...
select p from parent where all(parent.children.haircolor) IN ('blonde','redhead')
或
select p from parent where parent.children.haircolor ALL IN ('blonde','redhead')
没想到这些会起作用,但值得一试。到目前为止,只有一件事奏效了......
select p from parent
where 0 = (select count(c) from p.children c
where c.haircolor NOT IN ('blonde','redhead')
)
我真的不希望对每一行都运行这样的计数查询,但我没有看到更好的机制。这并不完全让我感到惊讶,因为我想不出用普通 SQL 编写它的任何其他方式,但我也不是那里的专家。有没有更有效的方法来做到这一点?
【问题讨论】:
标签: jpa one-to-many jpql