Reputation: 15802
I want to write rest like method for entity update. In this case I retrieve entity id from url and data from request body. The issue is in binding id with bean. Because neither EntityManager nor Spring-Data Crud Repo haven't update(id, bean)
method. So I can set it myself
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String update(@PathVariable("id") Long id, @Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
user.setId(id); //Very bad
return "usersEdit";
}
user.setId(id); //Bad
repository.save(user);
return "redirect:/users/" + id;
}
or dismiss DRY and put id in forms as private field to. Is there are any other solutions?
Upvotes: 0
Views: 573
Reputation: 111
In Spring 3.1 a @ModelAttribute will be instantiated from a path variable if the path variable and the model attribute names are the same and there is a converter to instantiate the model attribute from the path variable value:
@RequestMapping(value="/{account}", method = RequestMethod.PUT) public String update(@Valid @ModelAttribute Account account, BindingResult result) { if (result.hasErrors()) { return "accounts/edit"; } this.accountManager.saveOrUpdate(account); return "redirect:../accounts"; }
The full example is available at: https://github.com/rstoyanchev/spring-mvc-31-demo
Upvotes: 1