Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Mongo update by only not null fields of new POJO

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?

like image 776
iamcrypticcoder Avatar asked Jan 20 '26 09:01

iamcrypticcoder


1 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();
like image 165
Eklavya Avatar answered Jan 22 '26 23:01

Eklavya