Ohmen Ohmen - 1 month ago 17
Java Question

Ignore Entity Fields in REST Arguments in Spring Boot

I have an entity managed in a database and a controller which offers some CRUD operations on this entity.

Some fields in the Entity should not be changeable by the frontend which consumes the REST API. I simply want to ignore the values of this unchangeable fields and use the values from the DB instead.

Until now i did this in a method of my controller, which was called before I did the further work with the entity. But this approach feels bad to me so I looked for other solutions.

What can I do to move this preprocessing out of my Controller?

Answer

Here is a solution I can think of on top of my head:

You can create a view model class like MyObjVm that has a subset of the fields of your MyObj Entity class, which are changeable. In your controller, you can consume the MyObjVm object like so:

@RequestMapping(//...)
public String method(Model model, @RequestBody MyObjVm myObjVm) {
// ... 
// populate the MyObj entity from myObjVm so that only the changeable fields are consumed and assigned.
}  

The above shows how you consumes JSON from the frontend.

If you want to do the opposite, simply return the MyObjVm, of which the fields will be populated by MyObj's changeable fields. Your frontend will need to have a corresponding JS object to consume the returned JSON.

What can I do to move this preprocessing out of my Controller?

So the processing that needs to get out of your controller is pretty much the conversion between your view model and entity. You can create a helper class method dedicated to doing so.