如何制作动态DTO而不在Spring中发送完整的Payload

时间:2018-04-21 14:57:41

标签: java spring rest spring-boot dto

我的Spring控制器中有updateProvider(ProviderUpdateDto providerUpdt)方法,但是我没有看到需要发送提供者实体的整个有效负载,例如客户端只能更新名称或其他属性,即如果只需要更新一个字段,就没有必要发送整个实体,这在没有必要时会产生过多的带宽消耗。

什么是更好的做法,只发送要更新的字段并能够动态构建DTO?如果我使用Spring Boot,我该怎么办?建立我的API?

3 个答案:

答案 0 :(得分:1)

您可以使用杰克逊库,它提供注释@JsonInclude(Include.NON_NULL),并且只有非空值的属性才会传递给您的客户端。 查看链接http://www.baeldung.com/jackson-ignore-null-fields以获取示例。

答案 1 :(得分:0)

另一种选择是拥有一个DTO字段更改对象,这对象可以适用于您拥有的每个实体。 E.g:

class EntityUpdateDTO {
    // The class of the object you are updating. Or just use a custom identifier
    private Class<? extends DTO> entityClass;
    // the id of such object
    private Long entityId;
    // the fields you are updating
    private String[] updateFields;
    // the values of those fields...
    private Object[] updateValues;

}

json对象的示例:

{
    entityClass: 'MyEntityDTO',
    entityId: 324123,

    updateFields: [
        'property1',
        'property2'
    ],
    updateValues: [
        'blabla',
        25,

    ]
}

如果updateValues中的任何updateProvider(EntityUpdateDTO update);本身都是复杂的对象,可能会带来一些问题......

您的API将变为entityClass

如果您有每个DTO的更新API,那么您应该省略class字段,因为您已经知道您正在处理哪个{{1}}实体...

但是,除非您使用巨大的对象,否则我不会担心带宽。

答案 2 :(得分:0)

有许多技术可以改善带宽使用

  • 不漂亮打印Json
  • 启用HTTP GZIP压缩

然而,更重要的是确保你的API在逻辑上是合理的,省略一些字段可能会破坏业务规则,过细的API设计也会增加界面的复杂性