栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring JPA审核为空已创建

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring JPA审核为空已创建

您的(@)Controller类中的方法效率不高。您不想(手动)检索对象并将所有字段,关系等复制到该对象上。除了复杂的对象,您早晚或会遇到麻烦。

您想要的是第一种方法(用于显示表单的GET)来检索用户并将其存储在会话中

@SessionAttributes
。接下来,您需要一个带
@InitBinder
注释的方法将验证器设置为,
WebDataBinder
以便spring进行验证。这将使您的
updateFromForm
方法更干净。

@Controller@RequestMapping("/edit/{id}")@SessionAttributes("student")public EditStudentController    @Autowired      private StudentFormValidator validator;    @Autowired    private StudentRepository studentRep;    @InitBinder    public void initBinder(WebDataBinder binder) {        binder.setValidator(validator);    }    @RequestMapping(method=RequestMethod.GET)    public String showUpdateForm(Model model) {        model.addObject("student", studentRep.secureFind(id));        return "students/form";    }    @RequestMapping(method=RequestMethod.POST)    public String public String updateFromForm(@Valid @ModelAttribute Student student, BindingResult result, RedirectAttributes redirectAttributes, SessionStatus status)   {          // Optionally you could check the ids if they are the same.        if (result.hasErrors()) {   return "students/form";        }         redirectAttributes.addFlashAttribute("message", "?p?t???? p??s????!");        studentRep.save(student);        status.setComplete(); // Will remove the student from the session        return "redirect:/students/list";      }}

您将需要将

SessionStatus
属性添加到方法中并标记处理完成,以便Spring可以从会话中清理模型。

这样,您就不必在对象等周围复制。Spring会进行所有的升举,并且所有字段/关系都将正确设置。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437877.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号