我正在使用 Spring MVC 和 Spring Data 开发 REST API。
我正在使用 REST 公开一些实体,这些实体基本上具有自动生成的数据(ID、更新日期和创建日期)
public class Batch implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "hibernate_sequence")
private Integer id;
@Column(name = "create_date")
private Date createDate;
@Column(name = "update_date")
private Date updateDate;
// Getters/Setters for these fields
}
这是我的 Controller 如何设置来处理请求
@RequestMapping(value = "recipe/{id}/batch", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Batch> createBatch(@PathVariable Integer id, @RequestBody Batch batch)
{
batch.setRecipeId(id);
Batch in = batchService.createBatch(batch);
return new ResponseEntity<Batch>(in, HttpStatus.CREATED);
}
@RequestMapping(value = "recipe/{id}/batch/{batchId}", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<Batch> updateBatch(@PathVariable Integer id, @PathVariable Integer batchId, @RequestBody Batch batch)
{
Batch existing = batchService.getBatch(batchId);
batch.setId(batchId);
batch.setRecipeId(id);
batch.setCreateDate(existing.getCreateDate());
Batch in = batchService.saveBatch(batch);
return new ResponseEntity<Batch>(in, HttpStatus.OK);
}
最后是批量服务 public Batch createBatch(批量批处理) { 批量保存 = batchRepository.save(batch); 返回保存;
public Batch saveBatch(Batch batch)
{
return batchRepository.save(batch);
}
当将这些字段输入处理它的服务时,我该如何最好地防止这些字段被更新?我应该只是从 REST 的 PUT/POST 版本中手动将它们复制到服务中,还是有更好的方法从 API 中过滤掉这些字段的数据。当我有大约 15 种不同的资源时,手动复制它们听起来也很乏味。
我仍然希望在用户对资源执行 GET 时显示它们,我只是不想要它们提供的任何值,但我真的找不到如何管理它的好例子。
最佳答案
您应该将 create_date 或 id 等字段标记为“不可更新”,以避免覆盖现有值
@Column(name = "create_date", insertable = true, updatable = false)
关于java - Spring REST API 并防止更改自动生成的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18222011/