2015-07-19 79 views
0

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= 

我们应该设置usernamehg,但怎么办我们处理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" 
} 

如图所示,我们要检查模型的性能,这将是乏味的,一旦模型有一些深层次的嵌套豆。

处理这种情况时,什么是你的一般的做法?

回答

0

最好的做法是使用所提PATCH方法如果被发送的部分(在字段的含义)请求。然后,请求中的所有字段都应该被修改 - 设置为空值,例如

当涉及到PUT时,您不应该接受部分请求 - 因为这与标准不兼容。当请求在语法上正确时,您应该修改所有字段,除非数据库约束阻止您这样做。所以如果一个特定的用户可以(根据系统)将位置设置为空值,他/她应该被允许这么做。如果这是不可能的,你应该提出错误的请求异常,并返回400条状态码和消息。

+0

@hguser,如果我的答案帮助了你,请注册并接受它。 – Opal