I cannot update my object using PUT

Asked

Viewed 32 times

-1

Although I know very little about Spring because I am learning, I cannot save a recovered object, the error is when I pass the object personal Pository.save(personSalva) I came to see some examples, but I found it difficult to understand due to the little knowledge I still have.

@PutMapping("/{codigo}")
public ResponseEntity<Optional<Pessoa>> atualizar(@PathVariable Long codigo, @RequestBody Pessoa pessoa) {
    Optional<Pessoa> pessoaSalva = pessoaRepository.findById(codigo);
    BeanUtils.copyProperties(pessoa, pessoaSalva, "codigo");
    pessoaRepository.save(pessoaSalva);
    
    return !pessoaSalva.isEmpty() ? ResponseEntity.ok(pessoaSalva) : ResponseEntity.notFound().build();
}

2 answers

1

Good evening @dayson Rodrigues, it would be correct to have a form class or simply put the entity in the parameter, spring boot has the ability to convert the data coming from HTML pro java, as long as they have the same name and type, so it can receive the data with vc only needing to call the save() method passing the entity received by the parameter, which normally the method should update if the id is not null and save if the id is null, I will leave a link from a repository, just take a little peek that will make things easier ;)

Your method would look like this:

@RequestMapping(value="/salvar", method=RequestMethod.POST)
//aqui já recebendo os campos com o mesmo nome dos atributos da entidade
public Pessoa salvar(Pessoa pessoa) { 
   if(pessoa != null){
    return pessoaRepository.save(pessoa);
   }
   return null;
}

https://github.com/rattherootkit/calendar

0

I believe it’s because I’m not checking whether the Optional is empty or not, for example:

Pessoa pessoaSalva = pessoaRepository.findById(codigo);
  if(pessoaSalva.isEmpty(){
   \\lançar uma exceção aqui
}

Browser other questions tagged

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