Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将仅获取选定子实体与父实体联接_Java_Spring_Jpa_Spring Data_Jpql - Fatal编程技术网

Java 如何将仅获取选定子实体与父实体联接

Java 如何将仅获取选定子实体与父实体联接,java,spring,jpa,spring-data,jpql,Java,Spring,Jpa,Spring Data,Jpql,我试图通过ID仅选择父实体旁边的某些实体。这可能吗?示例样板省略: class Parent { int id; List<Child> children; } class Child { int id; ... } 将返回仅附加了3个子实体的父对象,但取而代之的是所有子对象,即ID为1-10的子对象。这没有任何意义,因为需要获取整个实体图。考虑一个父P有子C1、C2和C3,并且只有C1和C2的ID传递给方法。如果您仅获取具有c1和c2的父实体,那么如果执

我试图通过ID仅选择父实体旁边的某些实体。这可能吗?示例样板省略:

class Parent {
   int id;
   List<Child> children;
}

class Child {
   int id;
   ...
}

将返回仅附加了3个子实体的父对象,但取而代之的是所有子对象,即ID为1-10的子对象。

这没有任何意义,因为需要获取整个实体图。考虑一个父P有子C1、C2和C3,并且只有C1和C2的ID传递给方法。如果您仅获取具有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
考虑创建从子级到父级的双向关系,并仅从ChildRepository获取子实体:

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)
}

这样,您不仅可以获得所需的子实体,还可以从任何子实体访问父实体。get0.getParent。

好的,谢谢。有道理。需要自下而上,而不是自上而下。@OgnjenMišić没错,祝你有一个美好的一天!
p = parentRepo.getParentByIdAndChildIds(1, Arrays.asList(1,2));
parentRepo.save(p); // is the relationship between p and c3 destroyed
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)
}