Spring Mongo update by only not null fields of new POJO

Viewed 4695

UserModel:

@Document(collection = "USER")
public class UserModel {
    private String id;
    private String username;
    @Indexed(unique = true)
    private String email;
    private String password;
    private String firstName;
    private String lastName;
}

UserRepository:

@Repository
public interface UserRepository extends MongoRepository<UserModel, String> {

    Optional<UserModel> findByEmail(String email);
    Optional<UserModel> findByUsername(String username);
}

Saving user document like this:

@Autowired
UserRepository userRepo;

public someMethod() {
    UserModel user = new UserModel();
    //Set all fields....
    userRepo.save(user);
}

Trying to update like this:

@Autowired
UserRepository userRepo;

public someMethod() {
    UserModel user = new UserModel();
    user.setId("A valid Id got from database by last insert")
    user.setFirstName("New first name");
    // Remaining fields are null now
    userRepo.save(user);
}

Here null values will be inserted by MongoRepository.

In there any setup by which I can tell MongoRepository to avoid null values while updating?

If we do this by MongoTemplate updateFirst() method we have to add if conditions for all fields of a POJO. What is the best solution in this case?

2 Answers

Try to fetch first from the database the user then updates your data and save in the database.

UserModel user = userRepo.findById(id); // Fetch from database
user.setFirstName("New first name");    // Update the data
userRepo.save(user);                    // Save in the database

Or use custom query to update only selected fields. Here to make it dynamic, create a Map<String, Object> from UserModel and remove null value.

ObjectMapper oMapper = new ObjectMapper();
Map<String, Object> dataMap = oMapper.convertValue(user, Map.class);
map.values().removeIf(Objects::isNull);

And now set the map in Update then update in the database.

Update update = new Update();
dataMap.forEach(update::set);
Query query = new Query().addCriteria(where("_id").is(id));
mongoTemplate.update(UserModel.class).matching(query).apply(update).first();

I user an extra class UserUpdateParam to collect values,then use Mapstruct to convert UserUpdateParam to UserModel with annotation @BeanMapping to ignore null value. Here is my solution:

UserModel:

@Document(collection = "USER")
public class UserModel {
    private String id;
    private String username;
    @Indexed(unique = true)
    private String email;
    private String password;
    private String firstName;
    private String lastName;
}

UserUpdateParam:


public class UserUpdateParam {
    private String id;
    private String username;
    private String email;
    private String password;
    private String firstName;
    private String lastName;
    
    public UserUpdateParam(){}
}

UserMapper:

import org.mapstruct.BeanMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.NullValuePropertyMappingStrategy;

@Mapper(componentModel = "spring")
public interface UserMapper {

    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    void toModel(UserUpdateParam userUpdateParam, @MappingTarget UserModel userModel);
}

update Code:

class UserDaoImpl {
    @Autowired
    private UserMapper userMapper;
    @Autowited
    private MongoTemplate mongoTemplate;

    public void update(UserUpdateParam userUpdateParam) {
        Query query = new org.springframework.data.mongodb.core.query.Query();
        query.addCriteria(Criteria.where("_id").is(userUpdateParam.getId()));
        UserModel userMdoel = mongotemplate.findOne(query, UserModel.class);
        if (userModel == null) {// expr}
        userMapper.toModel(userUpdateParam, userModel);
        mongoTemplate.save(userModel);
    }
}
Related