Spring Partial Update Object Data Binding

后端 未结 8 1719
挽巷
挽巷 2020-12-02 08:26

We are trying to implement a special partial update function in Spring 3.2. We are using Spring for the backend and have a simple Javascript frontend. I\'ve not been able to

8条回答
  •  -上瘾入骨i
    2020-12-02 09:10

    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 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.

提交回复
热议问题