Spring MVC 3.0:如何绑定到持久对象 [英] Spring MVC 3.0: How do I bind to a persistent object

查看:108
本文介绍了Spring MVC 3.0:如何绑定到持久对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  @RequestMapping(/ save)
public String save(@ModelAttribute(item)BenefitType benefitType,BindingResult result)
{
...检查错误
...保存等
}


解决方案

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

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


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.
}

解决方案

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
}

这篇关于Spring MVC 3.0:如何绑定到持久对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆