选择父实体,其中给定的set(参数)是JPA Query中ManyToMany关系中Parent的子集的精确子集

问题描述 投票:1回答:1

假设父实体是Parent。它与孩子ManyToManyChild关系。

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

和孩子,

@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<Resource> parents;
}

假设我们的父实体是,

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的父母。因此,在这种情况下,父母将是parent1parent4parent5。 (不接受parent2和parent3,因为他们没有childAchildC

我的JPA接口方法签名。

List<Resource> findParentByChilds (@Param("childs") Set<Child> childs)
spring-boot jpa spring-data-jpa jpa-2.0 jpql
1个回答
1
投票

这是一个使用SQL的简单解决方案

SELECT parent_id
FROM child_parent
WHERE child_id IN ('childA', 'childC')
GROUP BY parent_id
HAVING COUNT(DISTINCT child_id) = 2

如果父母不能拥有相同的孩子两次(例如,你在(parent_id, child_id)上有一个唯一的密钥,那么你可以从DISTINCT聚合函数中删除COUNT()

将它转换为JPQL应该是直截了当的,或者您只是使用本机SQL查询。

© www.soinside.com 2019 - 2024. All rights reserved.