Spring Partial Update Object Data Binding

I’ve just run into this same problem. My current solution looks like this. I haven’t done much testing yet, but upon initial inspection it looks to be working fairly well.

@Autowired ObjectMapper objectMapper;
@Autowired UserRepository userRepository;

@RequestMapping(value = "/{id}", method = RequestMethod.POST )
public @ResponseBody ResponseEntity<User> update(@PathVariable Long id, HttpServletRequest request) throws IOException
{
    User user = userRepository.findOne(id);
    User updatedUser = objectMapper.readerForUpdating(user).readValue(request.getReader());
    userRepository.saveAndFlush(updatedUser);
    return new ResponseEntity<>(updatedUser, HttpStatus.ACCEPTED);
}

The ObjectMapper is a bean of type org.codehaus.jackson.map.ObjectMapper.

Hope this helps someone,

Edit:

Have run into issues with child objects. If a child object receives a property to partially update it will create a fresh object, update that property, and set it. This erases all the other properties on that object. I’ll update if I come across a clean solution.

Leave a Comment