简体   繁体   中英

Java Optional, delete value and return, is there a better way?

public Optional<ReligiousOrderEntity> deleteReligiousOrderEntity( Long id){
    religiousOrderRepository.findById(id)
        .ifPresent( religiousOrderRepository::delete );
    
    return religiousOrderRepository.findById(id);
}

That is my code but I don't feel good about it. Looks to me that there should be a better way using Optionals.

The religiousOrderRepository.findById(id) returns an Optional with a ReligiousOrderEntity on it, but before returning, we need to delete it.

(don't worry about the delete function, you can assume it works)

If you find an entry, you delete it, then you try to find something again for the return value. That will always be an empty Optional because of the deletion.

You need to remember the value returned by the first findById :

public Optional<ReligiousOrderEntity> deleteReligiousOrderEntity(Long id){
    Optional<ReligiousOrderEntity> opt = religiousOrderRepository.findById(id)
    opt.ifPresent(religiousOrderRepository::delete);
    return opt;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM