我试图通过 id 仅选择父实体旁边的某些实体。这可能吗?示例(省略样板):
class Parent {
int id;
List<Child> children;
}
class Child {
int id;
...
}
还有我的 JpaRepository:
interface ParentRepo extends JpaRepo<Parent,Integer> {
@Query("SELECT p FROM Parent p JOIN p.children c WHERE p.id = :parentId and c.id IN(:childIds")
Parent getParentByIdAndChildIds(int parentId, List<Integer> childIds)
}
我的期望是调用:
parentRepo.getParentByIdAndChildIds(1, Arrays.asList(1,2,3))
将返回仅附加 3 个子实体的父对象,但相反,我得到所有子实体(即 id 为 1-10 的子实体)。
最佳答案
这没有任何意义,因为需要获取整个实体图。考虑一位家长p
有 child c1
, c2
和c3
并且只有 c1
的 ID和c2
被传递给你的方法。如果你获取 Parent
实体 c1
和c2
只是,如果你这样做,会发生什么:
p = parentRepo.getParentByIdAndChildIds(1, Arrays.asList(1,2));
p.getChildren().add(c3);
parentRepo.save(p); // what happens?
创建一个新的子项没有意义,因为数据库中已经存在一个子项。另一方面,jpa 的默认行为会删除 p
之间的关系。和c3
保存时不修改:
p = parentRepo.getParentByIdAndChildIds(1, Arrays.asList(1,2));
parentRepo.save(p); // is the relationship between p and c3 destroyed
考虑创建双向关系(也是从 Child
到 Parent
)并获取 Child
仅实体(来自 ChildRepository
):
interface ChildRepository extends JpaRepository<Child, Integer> {
@Query("SELECT c FROM Child c WHERE c.parent.id = :parentId and c.id IN(:childIds)")
List<Child> getParentByIdAndChildIds(int parentId, List<Integer> childIds)
}
这样你就只能得到Child
您想要的实体,还有 Parent
可以从任意 Child
访问(children.get(0).getParent()
)。
关于java - 如何将仅获取选定的子实体与父实体连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60941535/