Tuesday, 13 August 2013

Spring REST API And preventing changes to auto generated properties?

Spring REST API And preventing changes to auto generated properties?

I am working on a REST API using Spring MVC and Spring Data.
I am exposing a few entities to with REST that have basically auto
generated data (ID, Update date and create date)
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
}
Here are is how my controller is setup for handling the request
@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.setUpdateDate(new Date());
Batch in = batchService.saveBatch(batch);
return new ResponseEntity<Batch>(in, HttpStatus.OK);
}
Then finally the batch service public Batch createBatch(Batch batch) {
Batch saved = batchRepository.save(batch); return saved; }
public Batch saveBatch(Batch batch)
{
return batchRepository.save(batch);
}
How best would I go about preventing these fields from being updated when
fed into the service that handles it? Should I just manually copy them in
the service from the version that was PUT/POST from REST or is there a
better way to filter out data for these fields from the API. Manually
copying them also sounds very tedious when I have roughly 15 different
resources.
I still want them to be displayed when a user does a GET on the resource,
i just don't want any values they supply but I can't really find a good
example of how to manage this.

No comments:

Post a Comment