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