gpt4 book ai didi

java - 实现PATCH操作Play - Java

转载 作者:行者123 更新时间:2023-12-01 09:28:46 24 4
gpt4 key购买 nike

我必须使用正文为 JSONPATCH 请求部分更新我的资源。下面是我的 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() 函数中捕获请求,以便我可以部分更新我的资源?我无法找到好的文档来了解 Play 的 PATCH 操作!框架。

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

最佳答案

这是在 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;
}

关于java - 实现PATCH操作Play - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com