9

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

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

Here is the use case :

  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)

Here is a code sample :

@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 ?

nono
  • 1,462
  • 1
  • 13
  • 21
  • 3
    Well, since you're looking for child entities, that method should be in the ChildRepository, and it should be named findByParent, and return children associated with a given parent entity. Something like `select child from Parent p inner join p.children child where p = :parent`. – JB Nizet Aug 28 '16 at 14:04
  • Will it work even if the relation is unidirectional? I'll give it a try. – nono Aug 28 '16 at 23:55
  • The same problem I am trying to solve without any luck. You can answer your question if able to solve it. [Related Question](https://stackoverflow.com/questions/31582224/how-to-get-paginated-child-lists-from-onetomany-unidrectional-parent-using-findb) – Sabir Khan Jun 14 '17 at 10:51
  • I just did what @JBNizet mentioned. – nono Jun 22 '17 at 06:34

2 Answers2

6

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

And you can use it like this :

Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));
nono
  • 1,462
  • 1
  • 13
  • 21
  • I tried doing some thing similar , could you please share some inputs on this post ?: https://stackoverflow.com/q/64491315/4005379 – Alferd Nobel Oct 23 '20 at 00:24
1

Assuming the parent is called "Parent" you can also do something like that:

repo.findAllByParent(parent, pageable);

Kfir Fersht
  • 71
  • 2
  • 2