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