【问题标题】:Is there a way to reduce the number of arguments on a Page return?有没有办法减少页面返回的参数数量?
【发布时间】:2019-12-19 20:14:36
【问题描述】:

我正在使用 Spring 在我的应用程序中实现分页,并且端点的返回是 Page。这个对象返回很多参数。有没有办法消除其中的一些?

存储库扩展了 JpaRepository

服务

@Autowired
ClientRepositoy clientRepositoy;

public List<Client> findAllList() {
    return clientRepositoy.findAll();
}

控制器

@Autowired
ServiceClient serviceClient;

@GetMapping("/clients")
public Page<Client> getClients() {
    List<Client> clients = serviceClient.findAllList();
    return new PageImpl<>(convertToDto(clients), PageRequest.of(0, 10), clients.size());
}

JSON 返回

{
    "content": [
        {
            "id": 1,
            "name": "TEST"
        }
    ],
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 10,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 1,
    "totalElements": 7,
    "last": true,
    "size": 10,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "first": true,
    "numberOfElements": 7,
    "empty": false
}

我想删除整个 Pageable 对象,例如:

"pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 10,
        "paged": true,
        "unpaged": false
    },

【问题讨论】:

    标签: java rest spring-mvc pagination


    【解决方案1】:

    所以我们在响应中使用了一个我们无法修改的类

    我们可以使用 mixin。

    如果您创建了 ObjectMapper bean,则可以指定您的 mixin,它将在序列化期间使用。

    它看起来像下面的代码。

    设置getter可见性的mixin。它将在序列化期间使用:

    public interface PageImplMixin {
        @JsonIgnore
        Pageable getPageable();
    }
    

    自己的对象映射器 bean,它被配置为在 pageimpl 类将被序列化时使用我们的 mixin:

    @Configuration
    public class JacksonConfig {
      @Bean
      public ObjectMapper objectMapper() {
        return new ObjectMapper().setMixIns(Map.of(PageImpl.class, PageImplMixin.class));
      }
    }
    

    一些理解这个概念的链接:

    JacksonMixInAnnotations Mix-In Annotations to reuse, decouple

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2011-11-23
      • 2019-02-16
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多