Optional is used to deal with null exception, for the background, refer to:
!Tired of Null Pointer Exceptions? Consider Using Java SE 8's "Optional"!
eg. we have below source code:
@Component("auditAwareImpl")
public class AuditAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName());
}
}
ofNullable allow the result to have null.
and here in CRUD operation:
public boolean updateMsgStatus(int contactId, String updatedBy){
boolean isUpdated = false;
Optional<Contact> contact = contactRepository.findById(contactId);
contact.ifPresent(contact1 -> {
contact1.setStatus(EazySchoolConstants.CLOSE);
contact1.setUpdatedBy(updatedBy);
contact1.setUpdatedAt(LocalDateTime.now());
});
Contact updatedContact = contactRepository.save(contact.get());
if( null != updatedContact && updatedContact.getUpdatedBy() != null){
isUpdated = true;
}
return isUpdated;
}
Here ifPresent() to prevent null before next step.
There are other methods of optional, isPresent(), isEmpty()
Reference:
!Guide To Java 8 Optional