【问题标题】:Hibernate HQL: How to select Parent entity if and only if ALL Child entities have a property with same value?Hibernate HQL:当且仅当所有子实体都具有相同值的属性时,如何选择父实体?
【发布时间】:2020-12-04 23:38:54
【问题描述】:

我猜我有两个实体具有双向 @OneToMany@ManyToOne 关联:

Parent -- 有很多 --> Child
Child 有一个boolean 属性x

我想选择Parent 实体,其中所有关联的Child 实体都将x 设置为true
例如,如果我有如下数据:

家长:

+-------+       
|   ID  | 
+-------+       
|   1   |  
+-------+       
|   2   |  
+-------+ 

孩子:

+-------+-------+-------+       
|   ID  | P.ID  |   x   |
+-------+-------+-------+       
|   1   |   1   | true  |
+-------+-------+-------+       
|   2   |   1   | true  |
+-------+-------+-------+
|   3   |   2   | true  |
+-------+-------+-------+       
|   4   |   2   | false | 
+-------+-------+-------+  

我想要一个返回 Parent 实体和 id 1 的 HQL 或 JPQL 查询。

有什么想法吗?

【问题讨论】:

    标签: hibernate jpa spring-data-jpa


    【解决方案1】:

    你可以执行这个查询:

    from parent p where p.ID in (select c.parent from child c where c.x=true) and p.ID not in (select c.parent from child c where c.x = false)
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用jpql查询

      select p from Parent p where p.children is not empty and not exists(
          select 1 from p.children c where c.x=false)
      

      实体:

      @Entity
      public class Parent {
         //...
      
         @OneToMany
         List<Child> children;
      
         //...
      }
      

      【讨论】:

      • “从 p.children 中选择 1”中的 1 是什么?
      • 您可以使用select c from 代替select 1 from。结果是一样的。 select 1 from 用于简化选择对象。如果 c.x=false 子查询返回 1,那么 not exists(1) = false。否则not exists(nothing) = true.
      猜你喜欢
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2011-06-11
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      相关资源
      最近更新 更多