【问题标题】:Spring REST API And preventing changes to auto generated properties?Spring REST API 并防止更改自动生成的属性?
【发布时间】:2013-08-15 19:57:44
【问题描述】:

我正在使用 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
}

这是我的控制器如何设置来处理请求

@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 时显示它们,我只是不希望它们提供任何值,但我真的找不到如何管理这个的好例子。

【问题讨论】:

    标签: java spring rest spring-mvc spring-data


    【解决方案1】:

    在您的代码中,您保存新批次,而不是合并现有批次,这是生成 ID 问题的根源,基本上,您应该做的是更新相关字段相关的现有实体,并保存更新的现有实体,这将合并您的更改。

    很丑,但我还没有看到更优雅的东西。

    【讨论】:

      【解决方案2】:

      您应该将 create_date 或 id 等字段标记为“不可更新”,以避免覆盖现有值

          @Column(name = "create_date", insertable = true, updatable = false)
      

      【讨论】:

      • 这对于更新方面非常有用,但允许人们输入 id 而不是自动生成的,这看起来像是我将手动处理的东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2018-12-29
      相关资源
      最近更新 更多