親エンティティでのみ選択子エンティティをフェッチに参加する方法

Ognjen筋肉:

私は、IDSによって、親と一緒にのみ、特定のエンティティを選択しようとしています。これは可能ですか?例(定型は省略しました):

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子エンティティと親オブジェクトを返しますが、その代わり、私は子供のALL(1-10からIDを持つすなわち子供)を取得します。

アンドロニカス:

全体のエンティティグラフをフェッチする必要があるため、それは、どんな意味がありません。親の考えてみましょうp子供をもつc1c2c3の唯一のID c1c2あなたのメソッドに渡されます。あなたはフェッチした場合Parentにエンティティをc1し、c2唯一のあなたは、このような何かを行う場合は、何が、起こります:

p = parentRepo.getParentByIdAndChildIds(1, Arrays.asList(1,2));
p.getChildren().add(c3);
parentRepo.save(p); // what happens?

データベースにすでに1が存在するため、新しい子を作成すると、意味がありません。一方、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あらゆるから到達可能ですChildchildren.get(0).getParent())。

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=375189&siteId=1