Spring Framework - 在DB中创建新对象而不是更新

时间:2010-09-22 16:52:05

标签: spring spring-mvc

我在Spring 3.0中编写了一个使用Hibernate连接到数据库的应用程序。我有一个更新表格的控制器。每当提交表单时,我希望显示的对象被更新,但是使用新的ID值创建新对象。我查看了“petclinic”样本,我看不出它是如何不同的。

POJO

public class Person
{
    private int id;

    @NotNull
    private String name;

    //getter/setter for id
    //getter/setter for name

}

控制器

public class PersonUpdateController
{
    //injected
    private PersonService personService;

    @RequestMapping(value="/person/{personId}/form", method=RequestMethod.POST) 
    public String updateForm(ModelMap modelMap, @PathVariable personId)
    {
        Person person = personService.getById(personId);
        modelMap.addAttribute(person);
        return "person/update";     
    }

    @RequestMapping(value="/person/{personId}", method=RequestMethod.POST)
    public String update(ModelMap modelMap, @Valid Person person, BindingResult bindingResult)
    {
        if(bindingResult.hasErrors())
        {
            modelMap.addAttribute(person);
            return "person/update";
        }

        personService.save(person);

        return "redirect:person/" + person.getId() + "/success";
    }
}

JSP

<spring:url value="/person/${person.id}" var="action_url" />
<spring:form action="${action_url}" modelAttribute="person" method="POST">

<spring:input name="name" path="name" />

<input type="submit" value="Save" />

</spring:form>

PersonService实施

public class HibernatePersonService
    implements PersonService
{
    //injected
    private SessionFactory sessionFactory;

    //other methods

    public void save(Person person)
    {
        Session session = sessionFactory.getCurrentSession();
        session.saveOrUpdate(person);
    }
}

1 个答案:

答案 0 :(得分:4)

Spring MVC对HTML表单没有任何魔力。由于表单只包含一个字段,因此只能在update方法中填充一个字段。所以,你有两个选择:

  • id作为隐藏字段传递:<spring:hidden path = "id" />。请注意,在这种情况下,您需要检查可能的安全后果(如果恶意人员更改了ID,会发生什么)。
  • 在会话中存储Person,以便表单中的数据用于更新存储的对象(请注意,如果在一个会话中打开表单的多个实例,则可能会造成干扰)。这就是它在Petclinic中的表现:

-

@SessionAttributes("person")
public class PersonUpdateController {
    ...

    @RequestMapping(value="/person/{personId}", method=RequestMethod.POST) 
    public String update(ModelMap modelMap, @Valid Person person, 
        BindingResult bindingResult, SessionStatus status) 
    { 
        ...
        personService.save(person);
        status.setComplete(); // Removes person from the session after successful submit
        ...
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id"); // For security
    }
}