弹簧数据 JPA.子实体的分页
我将 Spring Data JPA 与 Spring Boot 版本 1.3.6.RELEASE 与内存数据库一起使用.
I'm using Spring Data JPA with Spring boot version 1.3.6.RELEASE with in-memory database.
我想知道如何从父实体对子实体进行分页.将 fetch 设置为 LAZY 对我来说不是解决方案.
I'm wondering how to paginate the child entities from a parent entity. Setting fetch to LAZY is not a solution for me.
这是用例:
- Parent 与 Childentity 具有单向 oneToMany 关系.
- 一个Parent的Child数量可以达到100,000(LAZY不是解决办法)
- 我不想让所有孩子进行分页(出于 CPU 和内存原因)
- Parent has an unidirectional oneToMany relation with Child entity.
- The number of Child for one Parent can reach 100,000 (LAZY is not a solution)
- I don't want to fetch all the child to do the pagination (For CPU and Memory reason)
这是一个代码示例:
@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>{}
我在父存储库中尝试过此操作失败:
I've tried this in the Parent repository unsuccessfully :
Page<Child> findById(int id, Pageable pageable);
这将返回父实体,而不是子实体.
This returns a Parent entity, not a Child entity.
知道怎么做吗?
推荐答案
下面是一个代码示例,可以获取知道父实体的子实体.请注意,此查询将返回 Child 的分页结果.
Here is a sample of code that can fetch the child entities knowing the parent. Note that this query will return a paginated result of 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));
相关文章