【问题标题】:JPA Query - JPQL to select parents that have ALL children with a property in a SET of valuesJPA Query - JPQL 选择具有一组值中属性的所有子级的父级
【发布时间】: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


    【解决方案1】:

    尝试使用子查询。

    select p from parent where parent.children.haircolor IN ('blonde','redhead') and p not in (select p from parent where parent.children.haircolor not IN ('blonde','redhead'))

    【讨论】:

      【解决方案2】:

      您尝试在看起来像集合属性的地方使用 JPQL 路径表达式 - 您不能这样做。而是像这样进行连接:

      SELECT p FROM Parent p JOIN p.children c WHERE c.haircolor IN :hairColorCollection
      

      在上面,Parent 被假定为具有集合值属性 children 的实体,其中每个目标实体都有一个值 haircolor 属性。 :hairColorCollection 是一个参数,在执行查询之前应该设置为一个集合对象。

      【讨论】:

      • 计划添加集合参数,但这只是典型的内部连接。它将返回任何子项与集合匹配的实体。这里的问题是在返回父级之前需要所有子级匹配。
      猜你喜欢
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      相关资源
      最近更新 更多