Spring MVC 3.0:如何绑定到持久对象

发布于 2024-09-17 22:23:12 字数 327 浏览 3 评论 0原文

我正在使用 Spring MVC,我希望它从数据库绑定一个持久对象,但我不知道如何设置我的代码以在绑定之前调用数据库。例如,我试图将“BenefitType”对象更新到数据库,但是,我希望它从数据库获取该对象,而不是创建一个新对象,这样我就不必更新所有字段。

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

I'm working with Spring MVC and I'd like it to bind a a persistent object from the database, but I cannot figure out how I can set my code to make a call to the DB before binding. For example, I'm trying to update a "BenefitType" object to the database, however, I want it to get the object fromthe database, not create a new one so I do not have to update all the fields.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

东风软 2024-09-24 22:23:13

因此,我最终通过在类中使用同名的 @ModelAttribute 注释方法来解决这个问题。 Spring 在执行请求映射之前首先构建模型:

@ModelAttribute("item")
BenefitType getBenefitType(@RequestParam("id") String id) {
    // return benefit type
}

So I ended up resolving this by annotating a method with a @ModelAttribute of the same name in the class. Spring builds the model first before executing the request mapping:

@ModelAttribute("item")
BenefitType getBenefitType(@RequestParam("id") String id) {
    // return benefit type
}
巴黎夜雨 2024-09-24 22:23:13

虽然您的域模型可能非常简单,您可以将 UI 对象直接绑定到数据模型对象,但更可能情况并非如此,在这种情况下,我强烈建议您专门设计一个用于表单绑定的类,然后它和控制器中的域对象之间进行转换。

While it is possible that your domain model is so simple that you can bind UI objects directly to data model objects, it is more likely that this is not so, in which case I would highly recommend you design a class specifically for form binding, then translate between it and domain objects in your controller.

我乃一代侩神 2024-09-24 22:23:13

我有点困惑。我认为您实际上是在谈论更新工作流程?

您需要两个 @RequestMappings,一个用于 GET,一个用于 POST:

@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public String getSave(ModelMap model, @PathVariable Long id)
{
    model.putAttribute("item", benefitDao.findById(id));
    return "view";
}

然后在 POST 上实际更新字段。

在上面的示例中,您的 @ModelAttribute 应该已经填充了类似上述方法的方法,并且使用 JSTL 或 Spring tabglibs 之类的方法与表单支持对象结合绑定属性。

您可能还想查看 InitBinder 取决于您的用例。

I'm a little confused. I think you're actually talking about an update workflow?

You need two @RequestMappings, one for GET and one for POST:

@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public String getSave(ModelMap model, @PathVariable Long id)
{
    model.putAttribute("item", benefitDao.findById(id));
    return "view";
}

then on the POST actually update the field.

In you example above, your @ModelAttribute should already be populated with a method like the above method, and the properties be bound using something like JSTL or Spring tabglibs in conjunction with the form backing object.

You may also want to look at InitBinder depending on your use case.

随梦而飞# 2024-09-24 22:23:12

有几种选择:

  • 在最简单的情况下,当您的对象只有简单属性时,您可以将其所有属性绑定到表单字段(如果需要,隐藏),并在提交后获取完全绑定的对象。复杂的属性也可以使用 PropertyEditor 绑定到表单字段。

  • 您还可以使用会话在 GETPOST 请求之间存储对象。 Spring 3 通过 @SessionAttributes 注解(来自 宠物诊所样本):

    <前><代码>@Controller
    @RequestMapping("/owners/*/pets/{petId}/edit")
    @SessionAttributes("pet") // 指定要存储在会话中的属性
    公共类 EditPetForm {
    ...
    @InitBinder
    公共无效setAllowedFields(WebDataBinder dataBinder){
    // 禁止绑定敏感字段 - 用户无法覆盖
    // 会话中的值
    dataBinder.setDisallowedFields("id");
    }
    @RequestMapping(方法=RequestMethod.GET)
    公共字符串setupForm(@PathVariable(“petId”)int petId,模型模型){
    宠物 pet = this.clinic.loadPet(petId);
    model.addAttribute("宠物", 宠物); // 将属性放入会话中
    返回“宠物/表格”;
    }
    @RequestMapping(方法 = { RequestMethod.PUT, RequestMethod.POST })
    public String processSubmit(@ModelAttribute("pet") Pet pet,
    BindingResult结果,SessionStatus状态){
    new PetValidator().validate(pet, 结果);
    if (结果.hasErrors()) {
    返回“宠物/表格”;
    } 别的 {
    this.clinic.storePet(宠物);
    // 提交成功后清理session属性
    状态.setComplete();
    return "redirect:/owners/" + pet.getOwner().getId();
    }
    }
    }

    但是,如果在同一个会话中同时打开多个表单实例,这种方法可能会导致问题。

  • 因此,对于复杂情况,最可靠的方法是创建一个单独的对象来存储表单字段,并手动将该对象的更改合并到持久对象中。

There are several options:

  • In the simpliest case when your object has only simple properties you can bind all its properties to the form fields (hidden if necessary), and get a fully bound object after submit. Complex properties also can be bound to the form fields using PropertyEditors.

  • You may also use session to store your object between GET and POST requests. Spring 3 faciliates this approach with @SessionAttributes annotation (from the 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();
            }
        }
    }
    

    However this approach may cause problems if several instances of the form are open simultaneously in the same session.

  • So, the most reliable approach for the complex cases is to create a separate object for storing form fields and merge changes from that object into persistent object manually.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文