RESTful应用程序给定一个控制器,将创建/更新/删除/查询User
:与更新实体
Get /users query the list
Post /users add a new user
Get /users/1 query a single record
Delete /users/1 delete a single record
Put /users/1 update a single record
注意最后Put
方法来操作/users/1
这意味着识别1
的用户应与被更新请求中的数据。
但是假设用户认同1具有以下性质(部分):
{username:uname,location:sg}
现在给出以下要求:
PUT /user/1
username=hg
PUT /user/1
username=hg&location=
我们应该设置username
到hg
,但怎么办我们处理location
?它应该设置为空还是保留在数据库中?
一般我们可以使用像弹簧MVC中的数据绑定在控制器:
@RequestMapping(value="/{userId}",method="PUT")
public String update(@PathVariable String userId, User user){
//merge the model, suppose the `user` contains all the properties of the user
user = entityManager.merge(user);
entityManager.persist(user);
return "user/show"
}
在这种情况下,一旦这两个例子的请求被执行时,该位置将设置为空在数据库中,其可以是或不是客户想要的。
通常,我们应该使用Patch
来更新资源的部分属性,但不是所有的框架都支持该方法。
而且更重要的是,即使是Patch
方法支持这样的:
@RequestMapping(value="/{userId}",method="PATCH")
public String updatePartial(@PathVariable String userId, User user){
//just set the properties no null
User userInDB=entityManager.find(userId);
//iterator all the properties, set the property which is not null or empty to the userInDB
entityManager.persist(userInDB);
return "user/show"
}
如图所示,我们要检查模型的性能,这将是乏味的,一旦模型有一些深层次的嵌套豆。
处理这种情况时,什么是你的一般的做法?
@hguser,如果我的答案帮助了你,请注册并接受它。 – Opal