I have a problem with the my Controller code. GET works fine (both empty form + form populated from db), POST works fine only for creating new object, but doesn’t work for editing. Part of my @Controller class:
@RequestMapping(value = "/vehicle_save.html", method = RequestMethod.GET)
public String setUpForm(@RequestParam(value="id", required = false) Long id, ModelMap model) {
Vehicle v;
if (id == null) {
v = new Vehicle();
} else {
v = vehicleManager.findVehicle(id);
}
model.addAttribute("vehicle", v);
return "vehicle_save";
}
@RequestMapping(value = "/vehicle_save.html", method = RequestMethod.POST)
public String save(@ModelAttribute("vehicle") Vehicle vehicle, BindingResult result, SessionStatus status) {
vehicleValidator.validate(vehicle, result);
if (result.hasErrors()) {
return "vehicle_save";
}
if(vehicle.getId() == null) {
vehicleManager.createVehicle(vehicle);
} else {
vehicleManager.updateVehicle(vehicle);
}
status.setComplete();
return "redirect:vehicle_list.html";
}
The first method creates a vehicle object (including its ID). But the second method gets the same object without the ID field (set to null).
What could I do: manually set vehicle.setID(id from parameters) and then save it to database. This causes JPAOptimisticLockException + I don’t like that solution.
Is there a way to pass my Vehicle object with ID to the second method? BTW, I would like to avoid adding hidden ID field to the JSP.
the example you suggested is using session to store the value. the
@SessionAttributeis to bind an existing model object to the session. Look at the source code the class is annotated with@SessionAttributes("pet").Which means your model attribute named “pet” is getting stored in session.Also look at the code in processSubmit method of EditPetForm classI havnt used something like this before.But i guess putting ur id in session is the way