spring-bootspring-mvcjava-8spring-data-jpaeclipse-jee

Optional class in spring boot?


I'm developing an application that manages accounts. I made a Package named org.sid.entities where exists the IBanqueJob interface and below its code

package org.sid.metier;

import org.sid.entities.Compte;
import org.sid.entities.Operation;
import org.springframework.data.domain.Page;

public interface IBanqueMetier {
    public Compte consulterCompte(String CodeCompte);
    public void verser(String CodeCompte,double mt);
    public void retirer(String CodeCompte, double mt);
    public void virement(String Cp1, String Cp2, double mt);
    public Page<Operation> listOperation(String cp,int page,int size);


}

and the implementation of this interface, below is its code

package org.sid.metier;

import java.util.Date;

import org.sid.dao.CompteRepository;
import org.sid.dao.OperationRepository;
import org.sid.entities.Compte;
import org.sid.entities.Operation;
import org.sid.entities.Versement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BanqueMetierImpl implements IBanqueMetier {
    @Autowired
    private CompteRepository compteRepository;
    @Autowired
    private OperationRepository operationRepository;

    @Override
    public Compte consulterCompte(String CodeCompte) {


       Compte cp = compteRepository.findById(CodeCompte);

         if (cp == null)
            throw new RuntimeException("compte introuvable");
        return cp;
    }

i have an error in this line below that says "Type mismatch: cannot convert from Optional to Compte "

Compte cp = compteRepository.findById(CodeCompte);

Solution

  • findById returns an Optional of something, meaning that we either have a single result for a given id or we don't have anything for that.

    In order to unpack this Optional, what I usually advise to do is the following:

    Compte cp = compteRepository.findById(CodeCompte).orElseThrow(() -> new Exception("Element not found!");
    

    This will throw an exception in case we don't find anything for that specific id.

    In some cases is more beneficial to return some default value instead of throwing an exception. In this case we can use this:

    Compte cp = compteRepository.findById(CodeCompte).orElse(new Compte());
    

    or with a supplier:

    Compte cp = compteRepository.findById(CodeCompte).orElseGet(() -> new Compte());