How to Update Only Some Put Fields in Springboot

Asked

Viewed 323 times

0

Hello People Explaining speed the code this endpoint there is my route updating an already registered student I enter with the data I want to register and send to update function and la "Arrow" data the big problem is that it only works if I "Set" everything, because if I leave some field empty, this records in the database as null, I tried to make a conditional to see if the variables are null or not however when it enters the conditional of the strings, as "name" and "password" of execption, Anyway the question is : How to change only some fields in Put without ending up setting null in others? without creating other functions for this, because there are only 4 attributes, imagine if you were 40 and we had to make a function each combination of attributes used.

@PutMapping("/{id}")
@Transactional
public ResponseEntity<AlunoDto> atualizar(@PathVariable Long id,@RequestBody AttAlunoForm form) {
        Aluno aluno = form.atualizar(id, alunosRepository);
        return ResponseEntity.ok(new AlunoDto(aluno));
}
    public Aluno atualizar(Long id, AlunosRepository alunosRepository) {
        Aluno aluno = alunosRepository.getOne(id);
            aluno.setIdade(idade);
            aluno.setNome(nome);
            aluno.setSenha(senha);
            aluno.setRenda(renda);
    
        return aluno;
    }

1 answer

1

In case of partial update of the resource the PATCH method should be used instead of the PUT.

In the case of PUT the full representation of the resource being updated should be forwarded.

Put vs Patch - Medium

For the case of PATCH where there is the need to update only the attributes that were forwarded you can use an if to get this behavior.

    public Aluno atualizar(Long id, AlunosRepository alunosRepository) {
        Aluno aluno = alunosRepository.getOne(id);
        if(idade != null) aluno.setIdade(idade);
        if(nome != null) aluno.setNome(nome);
        if(senha != null) aluno.setSenha(senha);
        if(renda != null) aluno.setRenda(renda);
    
        return aluno;
    }
  • But that’s what I say, and if it was 40 fields, I’d set the 40 ?

Browser other questions tagged

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