Select Parent 实体,其中给定集(参数)是 JPA 查询中多对多关系中 Parent 的 child 集的精确子集

Select Parent Entity where given set (parameter) is exact sub set of Parent's child set in ManyToMany relation in JPA Query

假设 Parent 实体是 Parent。它与 child Child.

ManyToMany 关系
@Entity
public class Parent{
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinColumn(name="child_Id")
    private Set<Child> childs;
}

和Child,

@Entity
public class Child{
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "child_parent",
            joinColumns = @JoinColumn(name = "child_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "parent_id", referencedColumnName = "id"))
    Set<Parent> parents;
}

假设我们的 parent 实体是,

parent1 has child -> childA, childB, childC;
parent2 has child -> childB, childC;
parent3 has child -> childB, childC, childD;
parent4 has child -> childA, childC;
parent5 has child -> childA, childB, childC, childD;

现在我想查询所有那些同时具有childAchildC的parent。因此,在这种情况下,parent 将是 parent1parent4parent5。 (parent2和parent3不被接受,因为它们没有childAchildC在一起)

我的 JPA 接口方法签名。

List<Parent> findParentByChilds (@Param("childs") Set<Child> childs)

这是一个使用 SQL

的简单解决方案
SELECT parent_id
FROM child_parent
WHERE child_id IN ('childA', 'childC')
GROUP BY parent_id
HAVING COUNT(DISTINCT child_id) = 2

如果 parent 不能有相同的 child 两次(例如,您在 (parent_id, child_id) 上有一个唯一键,那么您可以从 [=13] 中删除 DISTINCT =]聚合函数。

将其转换为 JPQL 应该很简单,或者您只需使用本机 SQL 查询即可。