简体   繁体   English

Java 可选,删除值并返回,有没有更好的方法?

[英]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.在我看来,应该有更好的方法来使用 Optionals。

The religiousOrderRepository.findById(id) returns an Optional with a ReligiousOrderEntity on it, but before returning, we need to delete it. religiousOrderRepository.findById(id) 返回一个带有 ReligiousOrderEntity 的 Optional,但在返回之前,我们需要删除它。

(don't worry about the delete function, you can assume it works) (不用担心删除 function,你可以假设它有效)

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.由于删除,这将始终是一个空的 Optional。

You need to remember the value returned by the first findById :您需要记住第一个findById返回的值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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