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

non*_*ono 6 java jpa one-to-many spring-data spring-boot

我将 Spring Data JPA 与 Spring Boot 版本 1.3.6.RELEASE 与内存数据库一起使用。

我想知道如何从父实体对子实体进行分页。将 fetch 设置为LAZY对我来说不是解决方案。

这是用例:

  1. Parent与 Child entity有一个单向oneToMany 关系。
  2. 一个ParentChild数量可以达到100,000(LAZY不是解决方案)
  3. 我不想获取所有孩子来进行分页(出于 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>{}
Run Code Online (Sandbox Code Playgroud)

我在父存储库中尝试过这个失败:

Page<Child> findById(int id, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)

这将返回父实体,而不是子实体。

知道如何做到这一点吗?

non*_*ono 6

以下是可以获取了解父实体的子实体的代码示例。请注意,此查询将返回 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);
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));
Run Code Online (Sandbox Code Playgroud)