假设父实体是Parent
。它与孩子ManyToMany
有Child
关系。
@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;
现在我想查询所有那些有childA
,childC
的父母。因此,在这种情况下,父母将是parent1
,parent4
和parent5
。 (不接受parent2和parent3,因为他们没有childA
和childC
)
我的JPA接口方法签名。
List<Resource> 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_id, child_id)
上有一个唯一的密钥,那么你可以从DISTINCT
聚合函数中删除COUNT()
。
将它转换为JPQL应该是直截了当的,或者您只是使用本机SQL查询。