Spring Boot, ultilizar outro campo de busca além do @id

Asked

Viewed 1,387 times

2

I am making an API with Java with Spring boot and I would like it to search for CPF and not ID;

http://localhost:8080/pacientes/ID

http://localhost:8080/pacientes/Cpf (sera informado pelo usuario)
http://localhost:8080/pacientes/cpf->http://localhost:8080/pacientes/77777785558

and I have the following fields in the PATIENT class;

the ID would like to leave as this, so it create,deleta, and change, in the url, would like to search by CPF.

Domain class

@Entity
public class Paciente implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private Long cpf;
    private String nome;

    public Paciente() {}

    public Paciente(Integer id,Long cpf, String nome) {
        super();
        this.id = id;
        this.cpf = cpf
        this.nome = nome;
    }

    // GETTERS E SETTERS
}

Pacienterepository

@Repository
public interface PacienteRepository extends JpaRepository<Paciente, Integer> {

}

Pacienteresource

@RestController
@RequestMapping(value = "capientes")
public class PacienteResource {

    @Autowired
    PacienteService PacienteService;

    @GetMapping(value = "/{id}")
    public ResponseEntity<Paciente> buscar(@PathVariable Integer id) {
        Paciente obj = PacienteService.findId(id);
        return ResponseEntity.ok().body(obj);

    }
}

Patient service


@Service
public class PacienteService {

    @Autowired
    PacienteRepository repo;



    public Paciente findId(Integer id) {
        Optional<Paciente> obj = repo.findById(id); 
        return obj.orElseThrow(() -> new ObjectNotFoundException("Objeto não encontrado! ID: " + id + ", Tipo"+ PacienteService.class.getName()));

    }


    public Paciente insert (Paciente obj) {
        obj.setId(null);
        return repo.save(obj);
    }
    public Paciente update (Paciente obj) {
        findId(obj.getId());
        return repo.save(obj);
    }
    public void delete(Integer id) {
        findId(id);
        try {
            repo.deleteById(id);
        }   
        catch (DataIntegrityViolationException e) {
             throw new DateIntegrityException("Não é possível excluir uma Paciente ");

        }

    }
}

is working , however I need instead of searching for the ID, I want to search for Cpf, that the person informs, getting so:

http://localhost:8080/pacientes/77777788898788

Today he is seeking patient only by ID

http://localhost:8080/pacientes/1

1 answer

2


Your Repository should be able to search in the bank by CPF, thus:

@Repository
public interface PacienteRepository extends JpaRepository<Paciente, Integer> {

    Optional<Paciente> findByCpf(Long cpf);
}

In your service class PacienteService, now add the method to perform the CPF search:

public Paciente findCPF(Long cpf) {
    Optional<Paciente> obj = repo.findByCpf(cpf); 
    return obj.orElseThrow(() -> new ObjectNotFoundException("Objeto não encontrado! CPF: " + cpf + ", Tipo"+ PacienteService.class.getName()));
}

Finally, build your Endpoint in Resource PacienteResource:

@GetMapping(value = "/{cpf}")
public ResponseEntity<Paciente> buscar(@PathVariable Long cpf) {
    Paciente obj = PacienteService.findCpf(cpf);
    return ResponseEntity.ok().body(obj);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.