Pagination in Spring Data Rest for nested resources

前端 未结 1 1226
春和景丽
春和景丽 2021-01-15 18:48

When the below URL is visited, I get paginations in response

/api/userPosts/

{
  \"_links\" : {
    \"self\" : {
      \"href\" : \"/api/userPosts{?page,si         


        
1条回答
  •  逝去的感伤
    2021-01-15 19:10

    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 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.

    0 讨论(0)
提交回复
热议问题