我在查询方面遇到了一些麻烦,我希望得到的A类只有那些具有给定id的C的B。但是,如果A还有另一个B.C,它也正在加载。如果存在,如何使用给定的ID强制执行加载?
class A {
@OneToMany(mappedBy = "a", orphanRemoval = true)
private List<B> bList;
...
}
class B {
@ManyToOne
@JoinColumn(name = "aid", nullable = false)
private A a;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "cid", nullable = false)
private C c;
...
}
我尝试这样,但它不起作用:
@Query(value = "SELECT a from A a inner join a.b b where b.c.id in :#{#param.cIdSet} GROUP BY a HAVING COUNT(DISTINCT b) = :size")
List<A> findByCustom(@Param("param") AParam aSearchParam);
现在我喜欢这样,但它加载了不需要的实体:
...
List<B> bList = bRepository.findByCustomQuery(aSearchParam);
Set<A> aSet = bList.stream()
.map(B::getA)
.collect(Collectors.toSet());
......
return aSet.stream()
.filter(it -> bList.containsAll(it.bList()))
.collect(Collectors.toList());
答案 0 :(得分:0)
不确定是否有更简单的替代方案,但这应该有效:
select a from A a where :sizeOfCSet =
(select count(distinct b.id) from B b where b.a = :a
and b.c.id in :cIds)