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?