Spring REST partial update with @PATCH method

后端 未结 4 1973
感动是毒
感动是毒 2021-01-31 12:47

I\'m trying to implement a partial update of the Manager entity based in the following:

Entity

public class Manager {
    private int id;
    private Str         


        
4条回答
  •  梦毁少年i
    2021-01-31 13:19

    With this, you can patch your changes

    1. Autowire `ObjectMapper` in controller;
    
    2. @PatchMapping("/manager/{id}")
        ResponseEntity saveManager(@RequestBody Map manager) {
            Manager toBePatchedManager = objectMapper.convertValue(manager, Manager.class);
            managerService.patch(toBePatchedManager);
        }
    
    3. Create new method `patch` in `ManagerService`
    
    4. Autowire `NullAwareBeanUtilsBean` in `ManagerService`
    
    5. public void patch(Manager toBePatched) {
            Optional optionalManager = managerRepository.findOne(toBePatched.getId());
            if (optionalManager.isPresent()) {
                Manager fromDb = optionalManager.get();
                // bean utils will copy non null values from toBePatched to fromDb manager.
                beanUtils.copyProperties(fromDb, toBePatched);
                updateManager(fromDb);
            }
        }
    

    You will have to extend BeanUtilsBean to implement copying of non null values behaviour.

    public class NullAwareBeanUtilsBean extends BeanUtilsBean {
    
        @Override
        public void copyProperty(Object dest, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            if (value == null)
                return;
            super.copyProperty(dest, name, value);
        }
    }
    

    and finally, mark NullAwareBeanUtilsBean as @Component

    or

    register NullAwareBeanUtilsBean as bean

    @Bean
    public NullAwareBeanUtilsBean nullAwareBeanUtilsBean() {
        return new NullAwareBeanUtilsBean();
    }
    

提交回复
热议问题