使用JPA CRUD存储库查找子实体的计数

时间:2017-07-26 17:39:43

标签: java spring spring-data spring-data-jpa crud

我一直在使用JPA CRUD存储库默认方法,例如find,findAll,delete等,用于我的所有数据库操作。

现在我有两个实体:

@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;  
}

我有没有办法在ParentRepository中创建一个新方法,让我根据父级ID检索父级所有子级的计数?

所以在我的ParentRepository中,我可以创建一个看起来像这样的方法:

int findAllChildrenCount(Long parentID);

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

试试这些:

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