javaspring-bootrestmergeapache-commons-beanutils

Merge map properties to Java POJO


I'd like to implement UPDATE (method PUT) operation for REST api. From front-end application my controller method expects map of values, for example:

@PutMapping(value = "/profile")
public UserDto updateProfile(JwtAuthenticationToken jwtAuthenticationToken, @RequestBody Map<String, ?> userForm) {
...
}

I'd like to use map as the request body and not POJO because with help opf map I can declare 3 states for each property:

  1. property is absent in the map - property is not change, do not update the bean property
  2. property present and is not null - update bean property with value
  3. property present and is null - update bean property with null

with POJO I'm unable to handle #1 from the list above - the property is always present with null or not null value

In my service method I have to merge properties from the map with my User object based on the 3 rules above.

For sure, I can do it in my custom code with reflection api but looking for some existing util which can help me with this task... some kind of

user = BeanUtils.merge(userForm, user);

Please advise if any exists.


Solution

  • You can convert your User object to a Map and work as follow:

    Basically the code is something like that:

    private ObjectMapper objectMapper; 
    ...
    
    public User merge(User originalUser, Map newUserMap) {
       Map originalUserMap = objectMapper.convertValue(originalUser, Map.class);
       originalUserMap.putAll(newUserMap);
       return objectMapper.convertValue(originalUserMap, User.class);
    }
    
    ...
    User userAfterModifications = merge(user, userForm);
    ... //  Do what you need with the updated user
    

    Note that you need to be sure that the Map implementation supports null values.