Spring REST API并阻止更改自动生成的属性?

时间:2013-08-14 01:56:15

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

我正在使用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(批量批处理)     {         Batch saved = batchRepository.save(batch);         返回保存;     }

public Batch saveBatch(Batch batch)
{
    return batchRepository.save(batch);
}

如果将这些字段输入处理它的服务时,我最好如何防止这些字段被更新?我应该从REST的PUT / POST版本中手动复制它们,还是有更好的方法从API中过滤掉这些字段的数据。当我有大约15种不同的资源时,手动复制它们听起来也很乏味。

我仍然希望在用户对资源进行GET时显示它们,我只是不想要它们提供的任何值,但我真的找不到如何管理它的好例子。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

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

相关问题