I have onetomany unidrirectional parent - child.
I am fetching the child list using parent.
How do i apply pagination on the list of child records?
For Ex: Parent P has Child C1,C2,C3..C20
i do findByParentCode(Code) returns the Parent object with Child list in it. But i need to get the paginated list of the child.
Please Help
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can query your child object's table using the parent code field in the child object i.e the foreign key to the Parent table something like:
Page<Child> findByParentId(Long parentId, Pageable pageRequest);
You can paginate the query results by using Spring Data JPA pagination support. Create an instance of PageRequest class with the pageNumber, size and sorting if need be, and iterate over the pages as shown below
Page<Child> page = null;
do {
Pageable nextPageable = page != null ? page.nextPageable() : new PageRequest(0, pageSize);
page = childService.findByParentId(parentId, nextPageable);
processPage(page);
} while (page.hasNext());
回答2:
I have done pagination for the child list (which does not know its parent)
Query query = getEntityManager().createQuery(
"select s.chilidList from Parent s where s.ParentCode = :ParentCode");
query.setParameter("ParentCode", ParentCode);
query.setFirstResult(pageIndex);
query.setMaxResults(pageSize);