使用JPA CRUD存储库查找儿童实体的数量
问题描述:
我一直在使用JPA CRUD存储库缺省方法,例如find,findAll,delete等,以用于我所有的数据库操作。使用JPA CRUD存储库查找儿童实体的数量
现在我有两个实体:
@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);
答
尝试这些:
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
答
@Query("select size(u.children) from Parent u where u.id=:parentID")
int findAllChildrenCount(@Param("parentID")Long parentID);
+0
我试过'COUNT'并没有工作。 'SIZE'正在工作。谢谢 – BlueBird
不要忘了接受/给予好评的答案,帮助你... – Cepr0