I want to avoid null check while updating the value into database. but i need to update only the value that is coming from UpdateUserRequest object. how to avoid multiple null check? the source and destination has different name? do I need to use Map structs or BeanUtils.copyProperties or what is the best way to achieve these?
@Transactional
public void update(String userId, UpdateUserRequest updateUserRequest) {
dataRepository.findByUserId(userId)
.ifPresent(userTransaction -> {
if(updateUserRequest.getAccountId()!=null)
{
userTransaction.setAccountId(updateUserRequest.getAccountId());
}
if(updateUserRequest.getUserAmount()!=null)
{
userTransaction.setUserAmount(updateUserRequest.getUserAmount());
}
if(updateUserRequest.getSendDate() != null)
{
userTransaction.setUserRequestedDate(Date.valueOf(updateUserRequest.getSendDate()));
}
if(updateUserRequest.getDelDate() != null)
{
userTransaction.setDelDate(Date.valueOf(updateUserRequest.getDelDate()));
}
dataRepository.save(userTransaction);
});
}
you can avoid null checks by adding validations on the object level, spring provides
@Validannotation, you can check more here at baeldung to make object validated and avoid null checks, other options would be usingPreconditionsfrom google, or handling it on the entity level, which you annotate columns that are non null and let your method not check but rather just save and repository will throw because null was passed and you can handle the exception by returning some message or failed response, check here for making columns non null