使用 JPA CRUD 存储库查找 children 实体的计数
Finding a count of children entities using JPA CRUD Repository
我一直在使用 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 中创建一个新方法,让我可以根据 parent 检索 parent 的所有 Children 的计数身份证号?
那么在我的 ParentRepository 中,我可以创建一个看起来像这样的方法吗:
int findAllChildrenCount(Long parentID);
@Query("select size(u.children) from Parent u where u.id=:parentID")
int findAllChildrenCount(@Param("parentID")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);
}
我一直在使用 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 中创建一个新方法,让我可以根据 parent 检索 parent 的所有 Children 的计数身份证号?
那么在我的 ParentRepository 中,我可以创建一个看起来像这样的方法吗:
int findAllChildrenCount(Long parentID);
@Query("select size(u.children) from Parent u where u.id=:parentID")
int findAllChildrenCount(@Param("parentID")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);
}