我将 Spring Data JPA 与 Spring boot 版本 1.3.6.RELEASE 和内存数据库一起使用。
我想知道如何对子实体进行分页来自父实体。
将获取设置为LAZY对我来说不是一个解决方案。
这是用例:
-
Parent has an 单向与 Child 的一对多关系entity.
- 的数量Child对于一个Parent可以达到100,000(LAZY不是解决方案)
- 我不想获取所有子项来进行分页(出于 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);
这将返回父实体,而不是子实体。
知道怎么做吗?
以下是可以获取了解父实体的子实体的代码示例。
请注意,此查询将返回 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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)