I'm trying to implement DTO and am having a sizeable headache. I'd like some help. Here is my project, with spring boot 2.
I have 3 tables @entity as follows.
Abstract Client with only 1 attribute, the "id" and the respective get and set. 2 classes that inherit from client,
PersonPhysical
PersonalJuridica
each with their respective attributes (cpf, name, cnpj, business name ....) and methods.
I created 3 classes DTO, ClienteDTO, PFDTO and PJDTO.
In the ClientResource class, which is my @RestController, I have, among other methods, the insert method, which instead of using the Entity Client, I want it to use the ClientDTO
@PostMapping()
public ResponseEntity<Void> inserir(@RequestBody Cliente objetoCliente) {
objetoCliente = clienteService.inserir(objetoCliente);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(objetoCliente.getId()).toUri();
return ResponseEntity.created(uri).build();
}
And I want you to change that.
@PostMapping()
public ResponseEntity<Void> inserir(@RequestBody ClienteDTO objetoClienteDTO) {
Cliente objetoCliente = clienteService.converteParaDTO(objetoClienteDTO);
objetoCliente = clienteService.inserir(objetoCliente);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(objetoCliente.getId()).toUri();
return ResponseEntity.created(uri).build();
}
It turns out that in ClientService, my client service, the method converteParaDTO is giving error:
public Cliente converteParaDTO(ClienteDTO objetoClienteDTO) {
if (objetoClienteDTO instanceof PessoaFisicaDTO) {
return new PessoaFisica(objetoClienteDTO.getNome(), objetoClienteDTO., objetoClienteDTO.getRg(),
objetoClienteDTO.getEmail(), objetoClienteDTO.getDataDeNascimento(), objetoClienteDTO.getNaturalidade(),
objetoClienteDTO.getProfissao(), objetoClienteDTO.getGenero(), objetoClienteDTO.getEstadoCivil(), objetoClienteDTO.getPessoaFisicaTipo()) {
};
}
if (objetoClienteDTO instanceof PessoaJuridicaDTO) {
return new PessoaJuridica(objetoClienteDTO.getRazaoSocial(), objetoClienteDTO.getNomeFantasia(),
objetoClienteDTO.getDataDeConstituicao(), objetoClienteDTO.getInscricaoEstadual(), objetoClienteDTO.getInscricaoFederal(),
objetoClienteDTO.getPessoaJuridicaTipo());
}
return null;
}
The error is as follows: My ClientDTO has only 2 attributes, id and name. The other attributes and methods are specific to each class. So, the objectDAT.getSet () for example, does not exist, among others.
I wanted some help how I solve this problem. As I call one class or another (PFDTO or PJDTO) through a single method.