Spring Data JPA. 子实体的分页查询

9
我正在使用Spring Data JPA和Spring boot版本1.3.6.RELEASE以及内存数据库。我想知道如何从父实体中进行子实体的分页,将获取模式设置为LAZY对我来说不是解决方案。以下是用例:
1. 父实体与子实体之间有单向 oneToMany 的关系。
2. 一个父实体下可能会有10万个子实体(使用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);

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

有什么想法如何做到这一点吗?


3
好的,既然您正在寻找子实体,那么该方法应该在ChildRepository中,并且应该被命名为findByParent,返回与给定父实体关联的子实体。类似这样的语句:select child from Parent p inner join p.children child where p = :parent - JB Nizet
即使关系是单向的,它也能工作吗?我会试一试。 - nono
我一直在尝试解决同样的问题,但一直没有成功。如果您能够解决它,您可以回答您的问题。相关问题 - Sabir Khan
我刚刚做了@JBNizet提到的事情。 - nono
2个回答

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);

您可以像这样使用它:

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

我尝试过类似的事情,您能否在此帖子中分享一些意见?:https://stackoverflow.com/q/64491315/4005379 - Alferd Nobel

1
假设父级对象被称为“Parent”,您也可以这样操作: repo.findAllByParent(parent, pageable);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接