Hi, I have this code in one of my controllers:
@PutMapping("{id}")
public EntityDTO update(@PathVariable("id") String id, @RequestBody EntityDTO entityDTO) {
entityDTO.setId(id);
Entity entity = entityMapper.map(entityDTO);
Entity updated = entityService.save(entity);
return entityDTOMapper.map(updated);
}
I want to avoid the entityDTO.setId(id);
line and add the id
to the entityDTO
in an cleaner way, but I didn't find a suitable approach in Spring.
Using an argument resolver is a mess for such a simple task, but maybe it can be achieved injecting the id
in entityDTO
in the following way:
public class EntityDTO {
@PathVariable("id")
private String id;
...
}
Validation stuff should occur once the DTO is constructed.
I did a lot of research, and I found a lot of users wanting this feature or facing this problem of packaging the whole thing (body + query parameters) in a DTO before mapping to entity.
Comment From: mfolnovic
I've asked about this on SO 3 years ago: https://stackoverflow.com/questions/57905483/combining-pathvariable-and-requestbody. I'm still interested in this feature. :)
One extra point of view would be validation constraints, e.g. unique constraint on some field (on update, you also need to know id to implement it correctly).
Comment From: lbkulinski
Any update on this? It is something I would like to see as well. Thanks!
Comment From: rstoyanchev
This is a duplicate of #23618. You can also see some takes on this in https://github.com/spring-projects/spring-framework/issues/21770#issuecomment-453476735.