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 :
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 ?
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));
Assuming the parent is called "Parent" you can also do something like that:
repo.findAllByParent(parent, pageable)
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With