Spring MVC PATCH 方法:部分更新 [英] Spring MVC PATCH method: partial updates

查看:51
本文介绍了Spring MVC PATCH 方法:部分更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,我使用 Spring MVC + Jackson 来构建 REST 服务.假设我有以下 java 实体

I have a project where I am using Spring MVC + Jackson to build a REST service. Let's say I have the following java entity

public class MyEntity {
    private Integer id;
    private boolean aBoolean;
    private String aVeryBigString;
    //getter & setters
}

有时,我只想更新布尔值,我不认为发送带有大字符串的整个对象只是为了更新一个简单的布尔值是一个好主意.所以,我考虑过使用 PATCH HTTP 方法只发送需要更新的字段.因此,我在控制器中声明了以下方法:

Sometimes, I just want to update the boolean value, and I don't think that sending the whole object with its big string is a good idea just to update a simple boolean. So, I have considered using the PATCH HTTP method to only send the fields that need to be updated. So, I declare the following method in my controller:

@RequestMapping(method = RequestMethod.PATCH)
public void patch(@RequestBody MyVariable myVariable) {
    //calling a service to update the entity
}

问题是:我怎么知道哪些字段需要更新?例如,如果客户端只想更新布尔值,我将获得一个带有空aVeryBigString"的对象.我怎么知道用户只想更新布尔值,但不想清空字符串?

The problem is: how do I know which fields need to be updated? For instance, if the client just wants to update the boolean, I will get an object with an empty "aVeryBigString". How am I supposed to know that the user just wants to update the boolean, but does not want to empty the string?

我通过构建自定义 URL 来解决"了这个问题.例如,以下 URL: POST/myentities/1/aboolean/true 将映射到只允许更新布尔值的方法.此解决方案的问题在于它不符合 REST.我不想 100% 符合 REST,但我不喜欢提供自定义 URL 来更新每个字段(特别是考虑到当我想更新多个字段时会导致问题).

I have "solved" the problem by building custom URLs. For instance, the following URL: POST /myentities/1/aboolean/true will be mapped to a method that allows to only update the boolean. The problem with this solution is that it is not REST compliant. I don't want to be 100% REST compliant, but I do not feel comfortable with providing a custom URL to update each field (especially given that it causes problems when I want to update several fields).

另一种解决方案是将MyEntity"拆分为多个资源并仅更新这些资源,但我觉得这没有意义:MyEntity"一个普通资源,它不是<强>由其他资源组成.

Another solution would be to split "MyEntity" into multiple resources and just update these resources, but I feel like it does not make sense: "MyEntity" is a plain resource, it is not composed of other resources.

那么,有没有一种优雅的方法来解决这个问题?

So, is there an elegant way of solving this problem?

推荐答案

您可以将 boolean 更改为 Boolean 并为您不想更新的所有字段分配空值.唯一一个非空值将定义客户端要更新的字段.

You may change boolean to Boolean and assign null value for all fields that you don't want to update. The only one not null value will define you which field client want to update.

这篇关于Spring MVC PATCH 方法:部分更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆