【问题标题】:Implement PATCH operation Play - Java实现 PATCH 操作 Play - Java
【发布时间】:2016-09-22 06:35:41
【问题描述】:

我必须使用 PATCHrequest 部分更新我的资源,其正文是 JSON。下面是我的 OwnerDetails POJO。我在 Hibernate 中使用 play-framework。

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) 的实体对象创建了行。

PATCH 请求的 JSON 正文是,

PATCH /owners/123

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

我已经在路由文件中配置了正确的路由到方法。

这是应处理JSON 请求的OwnerController 类。我正在使用 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() 函数中捕获请求,以便我可以部分更新我的资源?我找不到好的文档来了解 PATCH Play 的操作!框架。

编辑:我已经看到有关 WSRequest 的补丁操作,但我不知道如何使用它。这会有帮助吗?

【问题讨论】:

    标签: java json hibernate playframework uri


    【解决方案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;
    }
    

    【讨论】:

    • 不工作。我收到JsonMappingException: Can not deserialize instance of 异常。 PATCH请求如何转换为Item类型?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2018-10-17
    • 2014-01-25
    • 2016-09-24
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多