I am using Spring 3 and Hibernate 4 to build my project.
My question is that for example, a User object has five fields, id, name, password, school and address. I only give the user the right to update/edit his school and/or address. When the user first access the edit page via GET,I want to populate the field with the user’s existing information.
Once submit button is clicked, I want to change the corresponding updated fields in my database via hibernate.
Controller.java
@RequestMapping(value="/edit/{userId}", method="RequestMethod.GET")
public String toEdit(Model model,@PathVariable int userId){
User user = userService.get(userId);
model.addAttribute("command",user);
return "/edit";
}
@RequestMapping(value="/save", method="RequestMethod.POST")
public String toSave(Model model){
//how to implement this?
}
edit.jsp
<form:form action="/save" method="POST">
<form:input path="school"/>
<form:input path="address"/>
<input type="submit"/>
</form:form>
My thought is that if I can put those fields that are not updated as hidden field in the edit.jsp page so that when the User object rebinds(when the form is submitted), I could still capture the user’s id, name and password information.
The pitfall of my approach is obvious. First, password as hidden field is never the way to go. Second, it adds unnecessary information on the edit.jsp page.
My second thought is that I could only put the user id as hidden field in the edit.jsp and when the form is submitted, I could use User user = userService.get(command.id) to get the corresponding user object and set the fields (e.g. school or address) to those newly entered ones by something like user.setSchool(command.getSchool()). After all of these, I can update the user object. This approach is kinda of troublesome, because if I got a lot of fields to update, there is gonna be a lot of code.
Is there a better way to do this? (I am sure there must be one) I am very new to Spring and Hibernate, so if I am missing something very obvious, please let me know.
Thanks.
If you use “dynamic-update” only modified fields will be updated.
You may ues the
@org.hibernate.annotations.Entityto mark your entity for dynamic updates.