2015-07-19 82 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