实现PATCH操作Play - Java

时间:2016-09-22 06:35:42

标签: java json hibernate playframework uri

我必须使用身体为PATCH的{​​{1}}请求部分更新我的资源。以下是我的PODO for OwnerDetails。我正在使用Hibernate的play-framework。

JSON

我在MySQL中为Entity Object创建了行,这些行对应于此值对象(VO)。

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; } } 请求的JSON正文是,

PATCH

我已在路径文件中配置了正确的路径。

以下是应该处理PATCH /owners/123 [ { "op": "replace", "path": "/name", "value": "new name" } ] 请求的OwnerController类。我正在使用POSTMAN发送请求。

JSON

如何在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 } } 函数中捕获请求,以便我可以部分更新资源?我无法找到好的文档来了解Play的update()操作!框架。

编辑:我已经看过WSRequest for Patch操作,但我不知道如何使用它。这会有帮助吗?

1 个答案:

答案 0 :(得分:1)

这是在Play Framework中使用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;
}