春季MVC 3.0:如何绑定到持久对象
-
01-10-2019 - |
题
我正在使用Spring MVC,我希望它可以从数据库中绑定AA持久对象,但是我无法弄清楚如何在绑定之前设置代码以调用DB。例如,我正在尝试将“ Benefitepe”对象更新为数据库,但是,我希望它从数据库中获取对象,而不是创建新的对象,因此我不必更新所有字段。
@RequestMapping("/save")
public String save(@ModelAttribute("item") BenefitType benefitType, BindingResult result)
{
...check for errors
...save, etc.
}
解决方案 2
因此,我最终通过用@modelattribute在同一名中使用@modelattribute的方法来解决此问题。春季在执行请求映射之前先构建模型:
@ModelAttribute("item")
BenefitType getBenefitType(@RequestParam("id") String id) {
// return benefit type
}
其他提示
有几个选择:
在最简单的情况下,当您的对象只有简单属性时,您可以将其所有属性绑定到表单字段(
hidden
如有必要),并在提交后获取一个完全绑定的对象。复杂的属性也可以使用PropertyEditor
s。您也可以使用会话在之间存储对象
GET
和POST
要求。春季3通过@SessionAttributes
注释(来自 Petclinic样品):@Controller @RequestMapping("/owners/*/pets/{petId}/edit") @SessionAttributes("pet") // Specify attributes to be stored in the session public class EditPetForm { ... @InitBinder public void setAllowedFields(WebDataBinder dataBinder) { // Disallow binding of sensitive fields - user can't override // values from the session dataBinder.setDisallowedFields("id"); } @RequestMapping(method = RequestMethod.GET) public String setupForm(@PathVariable("petId") int petId, Model model) { Pet pet = this.clinic.loadPet(petId); model.addAttribute("pet", pet); // Put attribute into session return "pets/form"; } @RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST }) public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) { new PetValidator().validate(pet, result); if (result.hasErrors()) { return "pets/form"; } else { this.clinic.storePet(pet); // Clean the session attribute after successful submit status.setComplete(); return "redirect:/owners/" + pet.getOwner().getId(); } } }
但是,如果同一会话同时打开表单的几个实例,则该方法可能会导致问题。
因此,对于复杂情况,最可靠的方法是创建一个单独的对象来存储表单字段,并将从该对象的对象合并为手动持久对象。
虽然您的域模型可能是如此简单,以至于您可以将UI对象直接绑定到数据模型对象,但很可能不是这样,在这种情况下,我强烈建议您设计专门用于形式绑定的类,在控制器中的IT和域对象之间翻译。
我有点困惑。我认为您实际上是在谈论更新工作流程?
您需要两个@requestmappings,一个用于获取,一个用于发布:
@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public String getSave(ModelMap model, @PathVariable Long id)
{
model.putAttribute("item", benefitDao.findById(id));
return "view";
}
然后在帖子上实际更新字段。
在上面的示例中,您的@ModelAttribute应该已经使用上述方法填充,并且使用诸如JSTL或Spring TabGlibs之类的属性与表单备份对象结合使用。
您可能还想看看 主张 取决于您的用例。