findOne无效,我更改为findById,但是返回类型出现问题

我在返回类型cp中出错:类型不匹配:无法从Optional转换为Compte

这是在使用eclipse的春季启动中

''Java 
@Service
@Transactional
public class BanqueMetierImpl implements IBanqueMetier{
@Autowired
 private COmpteRepository compteRepository;
 @Override
  public Compte ConsulterCompte(String codeCpte){
  Optional<Compte> cp=compteRepository.findById(codeCpte);
  if(cp==null)throw new RuntimeException("Compte Introuvable");
   return cp;

我正在尝试使用findOne,但无法正常工作,因此我使用findById的原因是返回类型cp时出现错误;

zys2229888 回答:findOne无效,我更改为findById,但是返回类型出现问题

此代码应该有效。

return cp.orElseThrow(()-> new RuntimeException("Compte Introuvable"));

我建议您看看此guide,以了解Optional的工作原理。

,

较新的Spring Data版本使用findById而不是findOne,并且现在返回null而不是返回Optional。它永远不会返回null,而是返回Optional.empty()

重写代码以正确使用Optional

@Override
public Compte ConsulterCompte(String codeCpte) {
  return compteRepository.findById(codeCpte)
           .orElseThrow(() -> new RuntimeException("Compte Introuvable"));
}

此外,您可能不应该抛出一般的RuntimeException而是抛出更具体的一个。

本文链接:https://www.f2er.com/3166966.html

大家都在问