Pagination in Spring Data Rest for nested resources

南楼画角 提交于 2019-12-02 04:56:23

Short painful answer: No. Absolutely not.

Long even more painful answer: Yes. By rewriting large sections of Spring Data, JPA and Hibernate. The core of the problem is that when you are requesting the the nested entity (collection or not) that nested entity is NOT queries from repository. But is is returned from the entity. There are no mechanics in Spring Data / JPA for paging

What /api/users/4/userPosts request in Spring REST does is basicly this:

User user = userRepository.findOne(4);
return user.userPosts;

So retrieving user.userPosts is Eager or Lazy reference to an nested entity and there is not way to page that.

Easiest and only solution to achieve this is : 1. create Spring Data search query: UserPostRepository.findByUserId(Long id, Pagination pa) 2. Create custom Spring MVC controller for mapping

   @Get("/api/users/{id}/userPosts")
   public Page<UserPost> getUserPostsByUserId(Long id, Pagination pagi) {
     return userPostRepository.findByUserId(id, pagi);
  1. Important! you must NOT! have user.userPosts annotated as nested in the User entity or request mapping will conflict.
  2. If you want the navigation hyperlinks for this path in User entity JSON then you need custom processing for User entity JSON creation. It is poorly documented and none of the examples cover this exact use case you you need to explore a bit.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!