Hibernate HQL:当且仅当所有子实体都具有相同值的属性时,如何选择父实体



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

CCD_ 3-具有许多->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 | 
+-------+-------+-------+  

我想要一个HQL或JPQL查询,它返回具有id1的Parent实体。

知道吗?

您可以执行以下查询:

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)

您可以像这样使用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;
//...
}

最新更新