【问题标题】:Update method in Rest like controllers像控制器一样在 Rest 中更新方法
【发布时间】:2011-11-10 02:21:09
【问题描述】:

我想为实体更新编写 rest like 方法。在这种情况下,我从 url 中检索实体 ID,从请求正文中检索数据。问题在于将 id 与 bean 绑定。因为 EntityManager 和 Spring-Data Crud Repo 都没有 update(id, bean) 方法。所以我可以自己设置

@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;
}

或关闭 DRY 并将 id 作为私有字段放入表单中。 还有其他解决办法吗?

【问题讨论】:

    标签: java hibernate rest spring-mvc spring-data


    【解决方案1】:

    在 Spring 3.1 中,如果路径变量和模型属性名称相同,并且有一个转换器从路径变量值实例化模型属性,则 @ModelAttribute 将从路径变量实例化:

    @RequestMapping(value="/{account}", 方法 = RequestMethod.PUT) public String update(@Valid @ModelAttribute Account account, BindingResult 结果) { if (result.hasErrors()) { 返回“帐户/编辑”; } this.accountManager.saveOrUpdate(account); 返回“重定向:../accounts”; }

    完整示例可在以下位置获得: https://github.com/rstoyanchev/spring-mvc-31-demo

    【讨论】:

      猜你喜欢
      • 2013-02-18
      • 2019-02-02
      • 2013-12-20
      • 2013-01-23
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多