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

pik*_*ike 1 java spring crud spring-data spring-data-jpa

我一直在使用 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;  
}
Run Code Online (Sandbox Code Playgroud)

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

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

int findAllChildrenCount(Long parentID);
Run Code Online (Sandbox Code Playgroud)

xyz*_*xyz 5

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