2017-07-26 8 views
1

私はすべてのデータベース操作に対してfind、findAll、deleteなどのJPA CRUDリポジトリのデフォルトメソッドを使用しています。JPA CRUDリポジトリを使用して子エンティティの数を見つける

今私は2つのエンティティがあります。

@Entity 
public class Parent implements Serializable { 

    @Id 
    @GeneratedValue 
    private long id; 

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE) 
    private Set<Child> children; 
} 

@Entity 
public class Child implements Serializable { 

    @Id 
    @GeneratedValue 
    private long id; 

    @ManyToOne 
    @JoinColumn 
    private Parent parent; 
} 

は私は私が親のIDに基づいて、親の全ての子どもの数を取得聞かせParentRepositoryで新しいメソッドを作成するための方法はあります?

だから私のParentRepositoryの内側に、私は次のようになります方法で作成できます。これらを試してみてください

int findAllChildrenCount(Long parentID); 
+0

は/助けupvote答えを受け入れることを忘れないでください。あなた... – Cepr0

答えて

0

を:

public interface ParentRepo extends JpaRepository<Parent, Long> { 

    Long countByChildren_Parent(Parent parent); 

    @Query("select count(c) from Parent p join p.children c where p = ?1") 
    Long countChildrenByParent(Parent parent); 

    Long countByChildren_ParentId(Long id); 

    @Query("select count(c) from Parent p join p.children c where p.id = ?1") 
    Long countChildrenByParentId(Long id); 
} 

public interface ChildRepo extends JpaRepository<Child, Long> { 

    Long countByParent(Parent parent); 

    @Query("select count(c) from Child c where c.parent = ?1") 
    Long countChildrenByParent(Parent parent); 

    Long countByParentId(Long id); 

    @Query("select count(c) from Child c where c.parent.id = ?1") 
    Long countChildrenByParentId(Long id); 
} 
+0

'COUNT'が@Queryで動作しているかどうか確認してください。私はそれがうまくいかないことを試みました。 'SIZE'を使うと、以下の@xyzの答えに従いました。 – BlueBird

2
@Query("select size(u.children) from Parent u where u.id=:parentID") 
int findAllChildrenCount(@Param("parentID")Long parentID); 
+0

私は 'COUNT'を試して、うまくいきませんでした。 'SIZE'が動作しています。ありがとう – BlueBird

関連する問題