【问题标题】:Spring Data JPA. Pagination for child entities弹簧数据 JPA。子实体的分页
【发布时间】:2017-01-04 15:34:32
【问题描述】:

我将 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>{}

我在父存储库中尝试过此操作失败:

Page<Child> findById(int id, Pageable pageable);

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

知道怎么做吗?

【问题讨论】:

  • 好吧,既然您正在寻找子实体,那么该方法应该在 ChildRepository 中,并且应该命名为 findByParent,并返回与给定父实体关联的子实体。类似于select child from Parent p inner join p.children child where p = :parent
  • 即使关系是单向的,它会起作用吗?我试试看。
  • 我试图解决的同样的问题没有任何运气。如果能够解决,您可以回答您的问题。 Related Question
  • 我刚刚做了@JBNizet 提到的。

标签: java jpa spring-boot spring-data one-to-many


【解决方案1】:

假设父母被称为“父母”,你也可以这样做:

repo.findAllByParent(parent, pageable);

【讨论】:

    【解决方案2】:

    这是一个代码示例,可以获取知道父实体的子实体。 请注意,此查询将返回 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));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 2014-03-28
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    相关资源
    最近更新 更多