简体   繁体   English

弹簧数据 JPA。 子实体的分页

[英]Spring Data JPA. Pagination for child entities

I'm using Spring Data JPA with Spring boot version 1.3.6.RELEASE with in-memory database.我将 Spring Data JPA 与 Spring Boot 版本 1.3.6.RELEASE 与内存数据库一起使用。

I'm wondering how to paginate the child entities from a parent entity.我想知道如何从父实体对子实体进行分页 Setting fetch to LAZY is not a solution for me.将 fetch 设置为LAZY对我来说不是解决方案。

Here is the use case :这是用例:

  1. Parent has an unidirectional oneToMany relation with Child entity . Parent与 Child entity有一个单向oneToMany 关系。
  2. The number of Child for one Parent can reach 100,000 (LAZY is not a solution)一个ParentChild数量可以达到100,000(LAZY不是解决方案)
  3. I don't want to fetch all the child to do the pagination (For CPU and Memory reason)我不想获取所有孩子来进行分页(出于 CPU 和内存原因)

Here is a code sample :这是一个代码示例:

@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.这将返回父实体,而不是子实体。

Any idea how to do this ?知道如何做到这一点吗?

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.请注意,此查询将返回 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);

And you can use it like this :你可以像这样使用它:

Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));

Assuming the parent is called "Parent" you can also do something like that:假设父母被称为“父母”,你也可以做这样的事情:

repo.findAllByParent(parent, pageable) ; repo.findAllByParent(parent, pageable) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM