Spring 数据 JPA。子实体的分页
Spring Data JPA. Pagination for child entities
我正在使用 Spring Data JPA 和 Spring 引导版本 1.3。6.RELEASE 和内存数据库。
我想知道如何从父实体分页子实体。
将 fetch 设置为 LAZY 对我来说不是解决方案。
这是用例:
- Parent 与 Child entity.
具有 unidirectional oneToMany 关系
- Child一个Parent的数量可以达到100,000(LAZY不是解决方案)
- 我不想获取所有子项来进行分页(出于 CPU 和内存原因)
这是一个代码示例:
@Entity
public class Parent{
@Id
private Integer id;
@OneToMany
private List<Child> childs;
}
@Entity
public class Child {
@Id
private Integer id;
}
public interface ParentRepository extends JpaRepository<Parent, Integer>{}
public interface ChildRepository extends JpaRepository<Child, Integer>{}
我在父存储库中尝试过此操作但未成功:
Page<Child> findById(int id, Pageable pageable);
此 returns 父实体,而不是子实体。
知道怎么做吗?
这是一个代码示例,可以获取了解父实体的子实体。
请注意,此查询将 return Child.
的分页结果
/**
* Find Child entities knowing the Parent.
*/
@Query("select child from Parent p inner join p.childs child where p = :parent")
public Page<Child> findBy(@Param("parent") Parent parent, Pageable pageable);
你可以这样使用它:
Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));
假设 parent 被称为 "Parent" 你也可以这样做:
repo.findAllByParent(parent, pageable)
;
我正在使用 Spring Data JPA 和 Spring 引导版本 1.3。6.RELEASE 和内存数据库。
我想知道如何从父实体分页子实体。 将 fetch 设置为 LAZY 对我来说不是解决方案。
这是用例:
- Parent 与 Child entity. 具有 unidirectional oneToMany 关系
- Child一个Parent的数量可以达到100,000(LAZY不是解决方案)
- 我不想获取所有子项来进行分页(出于 CPU 和内存原因)
这是一个代码示例:
@Entity
public class Parent{
@Id
private Integer id;
@OneToMany
private List<Child> childs;
}
@Entity
public class Child {
@Id
private Integer id;
}
public interface ParentRepository extends JpaRepository<Parent, Integer>{}
public interface ChildRepository extends JpaRepository<Child, Integer>{}
我在父存储库中尝试过此操作但未成功:
Page<Child> findById(int id, Pageable pageable);
此 returns 父实体,而不是子实体。
知道怎么做吗?
这是一个代码示例,可以获取了解父实体的子实体。 请注意,此查询将 return Child.
的分页结果 /**
* Find Child entities knowing the Parent.
*/
@Query("select child from Parent p inner join p.childs child where p = :parent")
public Page<Child> findBy(@Param("parent") Parent parent, Pageable pageable);
你可以这样使用它:
Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));
假设 parent 被称为 "Parent" 你也可以这样做:
repo.findAllByParent(parent, pageable)
;