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

查看:279
本文介绍了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: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?

推荐答案

您可以将布尔值更改为布尔值,并为您不想更新的所有字段分配空值。唯一一个非null值将定义您要更新的字段客户端。

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天全站免登陆