带Optional的重构方法到一行



我的Service中有一个更新现有组织的方法。

public Optional<Organisation> update(Organisation org) {
Optional<Organisation> optionalOrganisation = organisationRepository.findById(org.getId());
if (optionalOrganisation.isPresent()) {
Organisation organisationToUpdate = optionalOrganisation.get();
organisationRepository.save(organisationToUpdate);
}
return Optional.empty();
}

如何将此方法重构为一行?

应该是这样的:

public Optional<Organisation> update(Organisation org) {
return organisationRepository.findById(org.getId()) // what should be here?
Optional<Organisation> optionalOrganisation = organisationRepository.findById(org.getId())
optionalOrganisation.ifPresent(o -> { 
//update your object
} )
return optionalOrganisation;

你不需要保存,如果它是事务,它会自动保存

这就是我要找的:

public Optional<Organisation> update(Organisation org) {
return organisationRepository.findById(org.getId())
.map(organisationRepository::save);
}

最新更新