部分对象更新

时间:2016-05-01 09:49:52

标签: spring spring-mvc spring-rest

如何部分更新对象?

例如,创建对象"项目":

int

更新此项目:

curl -X POST -H "Content-Type:application/json" -d '
{ "name":"Project 1", "number": 123 }
' localhost:8080/myapp/projects
{
  "id" : 79,
  "number" : "123",
  "name" : "Project 1",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/myapp/projects/79"
    },
    "project" : {
      "href" : "http://localhost:8080/myapp/projects/79"
    }
  }
}

该物业"名称"现在是null。 如果未在更新请求中设置此属性,如何设置旧值对象属性?

我使用ProjectRepository的@RepositoryRestResource注释来指导Spring MVC在/ projects上创建RESTful端点

1 个答案:

答案 0 :(得分:0)

解决方案:使用PATCH http方法。

curl -i -X PATCH -H "Content-Type:application/json" -d '
{ "number": 124 }                    
' localhost:8080/myapp/projects/79
{
  "id" : 79,
  "number" : "124",
  "name" : "Project 1",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/myapp/projects/79"
    },
    "project" : {
      "href" : "http://localhost:8080/myapp/projects/79"
    }
  }
}