2016-09-22 36 views
0

我必須使用PATCH請求部分更新我的資源,其請求的主體是JSON。以下是我的OwnerDetails的POJO。我正在使用Hibernate的play-framework。執行PATCH操作播放 - Java

public class OwnerDetailsVO { 

    private int id; 
    private String name; 
    private int age; 

    public int getId() { 
     return id; 
    } 
    public void setId(int id) { 
     this.id = id; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public int getAge() { 
     return age; 
    } 
    public void setAge(int age) { 
     this.age = age; 
    } 
} 

我已經在MySQL中爲與此值對象(VO)對應的實體對象創建了行。

JSONPATCH請求是

PATCH /owners/123 

[ 
    { "op": "replace", "path": "/name", "value": "new name" } 
] 

我已經配置了正確的路線中的路由文件的方法。

以下是OwnerController類,它應該處理JSON請求。我正在使用POSTMAN發送請求。

public class OwnerController extends Controller { 

    public Result create() { 
    Form<OwnerDetailsVO> odVOForm = Form.form(OwnerDetailsVO.class).bindFromRequest(); 
     if(odVOForm.hasErrors()) { 
      return jsonResult(badRequest(odVOForm.errorsAsJson())); 
     } 

     OwnerDetailsVO odVO = odVOForm.get(); 
     int id = odProcessor.addOwnerDetails(odVO); 

     return jsonResult(ok(Json.toJson("Successfully created owner account with ID: " + id))); 
    } 

    public Result update(int id) { 
     //I am not sure how to capture the data here. 
     //I use Form to create a new VO object in the create() method 

    } 
} 

如何在update()函數內捕獲請求,以便我可以部分更新資源?我無法找到很好的文檔來了解關於Play的PATCH操作!框架。

編輯:我已經看過關於補丁操作的WSRequest,但我不知道如何使用它。這會有幫助嗎?

回答

1

這是使用ebeans在遊戲框架

public Item patch(Long id, JsonNode json) { 

    //find the store item 
    Item item = Item.find.byId(id); 
    if(item == null) { 
     return null; 
    } 

    //convert json to update item 
    Item updateItem; 
    updateItem = Json.fromJson(json, Item.class); 


    if(updateItem.name != null){ 
     item.name = updateItem.name; 
    } 
    if(updateItem.price != null){ 
     item.price = updateItem.price; 
    } 
    item.save(); 

    return item; 
} 
+0

不工作的樣本代碼。我得到'JsonMappingException:不能反序列化'異常的實例。如何將PATCH請求轉換爲'Item'類型? –