美文网首页
java.util.optional

java.util.optional

作者: 芒鞋儿 | 来源:发表于2023-02-27 20:34 被阅读0次

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

相关文章

网友评论

      本文标题:java.util.optional

      本文链接:https://www.haomeiwen.com/subject/ijkkldtx.html