Rocky Hu
Rocky Hu

Reputation: 1346

Can't update object which annotated with @ModelAttribute in Spring MVC

I have a method handle a get request, as below:

@RequestMapping(method = RequestMethod.GET)
public String edit(
        @ModelAttribute("deliveryFareTemplate") DeliveryFareTemplate deliveryFareTemplate,
        @RequestParam(required = true) Integer deliveryMethodId, Model model){
   DeliveryMethod deliveryMethod = deliveryMethodService.get(deliveryMethodId);
   DeliveryFareTemplate persistentEntity = deliveryFareTemplateService.get("deliveryMethodId", deliveryMethodId);
   if (persistentEntity == null) {
       // set some values manually
   } else {
       deliveryFareTemplate = persistentEntity;
   }

   return EDIT_VIEW;}

in my situation, the "persistentEntity" is not null, so it will execute the "else" fragment, but in my jsp view, I can't get any data from "deliveryFareTemplate", all the properties are null.

The attribute "deliveryFareTemplate" will auto be instantiated and put into the Model object. So we can get it in our view page. And if the "persistentEntity == null" is true, set data manually, they could be got. But why "deliveryFareTemplate = persistentEntity" don't work, I debug the code and found the data in "deliveryFareTemplate" had been updated, but still can't be got in view page.

Upvotes: 1

Views: 204

Answers (1)

Si mo
Si mo

Reputation: 979

with deliveryFareTemplate = persistentEntity you assign the instance of persistentEntity to deliveryFareTemplate. This will not work. You have to set the single attributes. Something like deliveryFareTemplate.copyProperties(persistentEntity) and in this method you copy the properties from the entity to the deliveryFareTemplate

Upvotes: 2

Related Questions