I have a DTO:
public class UserDto {
private Long id;
private String name;
}
and Controller:
@RestController
@RequestMapping("user")
public Class UserController {
@PostMapping(value = "{id}")
public String update(@PathVariable String id, @RequestBody UserDto userDto){
userDto.setId(id);
service.update(userDto);
}
}
What I don't like is manually putting ID from @PathVariable to DTO: userDto.setId(id);.
For POST request /user/5 with body: { name: "test" }, how could I automatically set ID in DTO, so that you'd get DTO like below?
{
id: 5,
name: "test"
}
Basically, I'd like to have something like:
@RestController
@RequestMapping("user")
public Class UserController {
@PostMapping(value = "{id}")
public String update(@RequestBody UserDto userDto){
service.update(userDto);
}
}
Is there a way to accomplish this?
Thank you! :)
EDIT: this is an old question, still unanswered, so I'd like to add new perspective to this question.
Another problem we had is validation, to specific - defining custom constraint that does validation based on some field and id.
if we remove id from request body, then how can we access it from custom constraint? :)
EDIT 2: italktothewind created issue on Github: https://github.com/spring-projects/spring-framework/issues/28637