Reputation: 191
I'm trying to update some persistent object in user form.
My POJO Class:
public Class MyModel {
int primKey;
String value;
// getter setter
}
Controller Methods:
@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public String getEditView(@PathVariable int id, ModelMap model) {
MyModel mymodel = modelService.getModel(id);
model.addAttribute("mymodel", mymodel);
return "/edit";
}
@RequestMapping(value="/update", method=RequestMethod.POST)
public String updateModel(@ModelAttribute("mymodel") MyModel mymodel, HttpSession session) {
session.setAttribute("status", modelService.update(mymodel) ? "success" : "error");
return "redirect:/home";
}
And my edit form:
<form:form modelAttribute="mymodel" role="form" method="post" action="/update">
<label>Enter new name:</label>
<form:input path="value"/>
<input type="submit" class="btn btn-default" value="Update" />
</form:form>
Now my question is when i receive model attribute "mymodel" in updateModel() method, "value" field is filled properly but "primKey" field is set to 0 which leads to failure in Hibernate Session's update method. Passing persistent object as "mymodel" makes it easier to display update form because all mapped values are set automatically and user can easily modify them. So is there any way to deal with this or i'll have to pass new MyModel attribute as model and update persistent object afterwards?
Upvotes: 1
Views: 1350
Reputation: 5420
Change int primKey;
to Integer primaryKey;
. By default int class variables are assigned 0, But Integer remains null.
I guess you want to auto generate the primaryKey
and save an new record (insert
). To do that primaryKey
has to be null
.
But since you are doing both the update and the insert in the same JSP template, you should have a hidden input binding for your primaryKey
.
But if you feel like the primaryKey is sensitive data you can Encode the primaryKey and keep it as a hiddenValue and then send it back, and decode it and get the actual value and use it.
Upvotes: 1
Reputation: 4692
As @SeanAdkinson pointed out you should change primKey
from int
to Integer
.
Also you should include a hidden field in your form for primKey
attribute. So that whenever there is a primKey then it is also submitted when you submit your form.
<form:hidden path="primKey"/>
Upvotes: 0
Reputation: 8605
primKey
is 0
because you are using int
instead of Integer
. int
cannot be null
, so it defaults to 0
if not specified. If you change your primKey
to be type Integer
, your form won't supply a value, and therefore primKey
will be null
, and Hibernate will happily save the object as a new record.
Upvotes: 0