gpt4 book ai didi

Spring MVC 3.0 : How do I bind to a persistent object

转载 作者:行者123 更新时间:2023-12-04 17:58:27 24 4
gpt4 key购买 nike

我正在使用 Spring MVC,我希望它从数据库中绑定(bind)一个持久对象,但我无法弄清楚如何设置我的代码以在绑定(bind)之前调用数据库。例如,我正在尝试将“BenefitType”对象更新到数据库,但是,我希望它从数据库中获取对象,而不是创建新对象,因此我不必更新所有字段。

    @RequestMapping("/save")
public String save(@ModelAttribute("item") BenefitType benefitType, BindingResult result)
{
...check for errors
...save, etc.
}

最佳答案

有几种选择:

  • 在最简单的情况下,当您的对象只有简单属性时,您可以将其所有属性绑定(bind)到表单字段(hidden 如有必要),并在提交后获得完全绑定(bind)的对象。复杂的属性也可以使用 PropertyEditor 绑定(bind)到表单域。 s。
  • 你也可以使用 session 在 GET 之间存储你的对象。和 POST要求。 Spring 3 通过 @SessionAttributes 促进了这种方法。注释(来自 Petclinic sample ):
    @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();
    }
    }
    }

    但是,如果表单的多个实例在同一 session 中同时打开,这种方法可能会导致问题。
  • 因此,对于复杂情况,最可靠的方法是创建一个单独的对象来存储表单字段,并手动将来自该对象的更改合并到持久对象中。
  • 关于Spring MVC 3.0 : How do I bind to a persistent object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3672100/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com