Spring Data JPA.对子实体的分页 [英] Spring Data JPA. Pagination for child entities

查看:87
本文介绍了Spring Data JPA.对子实体的分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Spring Data JPA与Spring引导版本1.3.6一起使用,并将其与内存数据库一起使用.

I'm using Spring Data JPA with Spring boot version 1.3.6.RELEASE with in-memory database.

我想知道如何从父实体对子实体进行分页. 将获取设置为 LAZY 并不是我的解决方案.

I'm wondering how to paginate the child entities from a parent entity. Setting fetch to LAZY is not a solution for me.

这是用例:

  1. 父母与孩子实体具有单向 oneToMany关系.
  2. 一个 Parent Child 的数量可以达到100,000(LAZY不是解决方案)
  3. 我不想让所有孩子去做分页(出于CPU和内存的原因)
  1. Parent has an unidirectional oneToMany relation with Child entity.
  2. The number of Child for one Parent can reach 100,000 (LAZY is not a solution)
  3. 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.

任何想法如何做到这一点?

Any idea how to do this ?

推荐答案

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

这篇关于Spring Data JPA.对子实体的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆