how to avoid null check on jpa update

79 Views Asked by At

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);
            });
}
2

There are 2 best solutions below

0
Mohammed Fataka On

you can avoid null checks by adding validations on the object level, spring provides @Valid annotation, you can check more here at baeldung to make object validated and avoid null checks, other options would be using Preconditionsfrom 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

0
minh tri Vo On

do I need to use Map structs or BeanUtils.copyProperties or what is the best way to achieve these?

Yes, for me, Mapstruct perfectly suits your purpose, for example:

@Mapper(uses = DateMapper.class)
public interface TestMapper {

    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) // if a source's property is null, ignore it
    @Mapping(source = "differentValue", target = "value") // Map to different property name
    void updateAppearanceFromDto(@MappingTarget Test mappingTarget, TestDto appearanceRequestDto); 
}

// help with different type cast
class DateMapper {
   public Date asDate(String date) {
      return Date.valueOf(date);
   }
}

Of course, if your project only requires the null-check-then-set on this entity only, manually doing it would be better because of the cost of dependency overhead.