我正在开发一个JPA / Jersey网络应用程序,想知道是否有更好的方法来更新记录。目前,我正在做:
@PUT
@Path("update/{id}")
@Produces("application/json")
@Consumes("application/x-www-form-urlencoded")
public Response createDevice(
@PathParam("id") int id,
@FormParam("name") String name,
@FormParam("type") int type
/*MultivaluedMap<String, String> formParams*/
) {
try {
Devices newDevice = entityManager.find(Devices.class, id);
if(name==null){name=newDevice.getName();}
if(type != newDevice.getType()){newDevice.setType(type);}
newDevice.setName(name);
//newDevice.setType(type);
entityManager.merge(newDevice);
return Response.status(201).entity(new ResponseObject("success")).build();
} finally {
entityManager.close();
}
}
这样可行,但是如果我的Devices表有更多字段,我将不得不检查所有字段与原始对象上的值是否相等,以查看它们是否已更改,以便我的
entityManager.merge(newDevice);
只会更改传入的值。
有更好的方法吗?