How to make a user changes with the PUT method in Springboot

Asked

Viewed 124 times

0

I’m doing a project and we’re in the API layer with Springboot. We have a problem with the verb PUT. We have the fields Id, Name, password, Tipousuario, password, so far so good, we are doing an If so that it identifies if there is an existing user with that name before updating, but our if does not let change the same person stating that there is already a user with the same name.

EX: I want to change the Tipousuario calling by id without changing the name of the person but he says I can not do because there is already someone with the same name.

@PutMapping("/atualizar")
public ResponseEntity<Usuario> Put(@RequestBody Usuario usuario) {
    Optional<Usuario> user = usuarioService.AtualizarUsuario(usuario);
    try {
        return ResponseEntity.ok(user.get());
    } catch (Exception e) {
        return ResponseEntity.badRequest().build();
    }

}

Here’s my upgrade PUT

I’m sorry if it’s not clear It’s the first time I’ve ever cast a doubt

Here is the user

package com.proagro.madeInRoca.service;

import java.nio.charset.Charset; import java.util.Optional;

import org.apache.Tomcat.util.codec.binary.Base64; import org.springframework.Beans.factory.Annotation.Autowired; import org.springframework.security.crypto.bcrypt.Bcryptpasswordencoder; import org.springframework.stereotype.Service;

import com.proagro.madeInRoca.model.Userlogin; import com.proagro.madeInRoca.model.Usuario; import com.proagro.madeInRoca.repository.Usuariorepository;

@Service public class Usuarioservice {

@Autowired
private UsuarioRepository repository;

public Optional<Usuario> CadastrarUsuario(Usuario usuario){

    if(repository.findByUsuario(usuario.getUsuario()).isPresent()) {
        return null;
    }

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String senhaEconder = encoder.encode(usuario.getSenha());

    usuario.setSenha(senhaEconder);

    return Optional.of(repository.save(usuario));
}

public Optional<Usuario> AtualizarUsuario(Usuario usuario){

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String senhaEconder = encoder.encode(usuario.getSenha());

    usuario.setSenha(senhaEconder);

    return Optional.of(repository.save(usuario));
}

public Optional<UserLogin> Logar(Optional <UserLogin> user){

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    Optional <Usuario> usuario = repository.findByUsuario(user.get().getUsuario());

    if(usuario.isPresent()) {
        if(encoder.matches(user.get().getSenha(), usuario.get().getSenha())) {

            String auth = user.get().getUsuario()+":"+user.get().getSenha();
            byte[]encodedAuth=Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
            String authHeader="Basic " + new String (encodedAuth);

            user.get().setToken(authHeader);
            user.get().setNome(usuario.get().getNome());
            user.get().setSenha(usuario.get().getSenha());
            user.get().setTipoUsuario(usuario.get().getTipoUsuario());

            return user;
        }
    }

    return null;
}

}

  • Cade the user code?

  • public Optional<Usuario> AtualizarUsuario(Usuario usuario){&#xA;&#xA; BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();&#xA; String senhaEconder = encoder.encode(usuario.getSenha());&#xA;&#xA; usuario.setSenha(senhaEconder);&#xA;&#xA; return Optional.of(repository.save(usuario));&#xA;}

  • Post spring error when trying to change

  • Edits the post and puts the whole part of the user related to the update. Only with this is not giving to see the problem.

  • @Franklinbarreto Alteirei the code, put the user service

  • Apparently what is happening is that it is not updating but trying to create a new record. When we are going to do an update, we have to pass the object id and fetch it in the database to be managed by JPA. If it’s not clear, let me know I put a code so you can understand.

  • @Franklinbarreto I get it, so it would be a findAll ?? Can you send me the code if possible ? I guess it wasn’t clear

  • @Franklinbarreto Thanks for your help, we managed to solve with your code.

  • @Heloisa would be nice so mark with useful answer (:

  • @Franklinbarreto still can’t move right, just confirm for me if I scored correctly please?

  • Yes yes @Heloisa

Show 6 more comments

1 answer

0


1° it is not a good practice to traffic their entities, but let’s leave it for later. You’re looking for an update, but you’re not looking for an object managed by jpa. Your code should look something like this.

@PutMapping("/atualizar/{id}")
public ResponseEntity<Usuario> Put(@RequestBody Usuario usuario, @PathVariable Long id) {
Usuario usuarioSalvo = usuarioService.findById(id).orlElseThrow(()-> new RuntimeExpection("Usuário não existe")); 
// Aqui você faz um mapeamento do que veio para o que já existe setando os dados e ai passa pro seu service mas eu colocaria a lógica no service e não aqui, foi só pra exemplificar
Optional<Usuario> user = usuarioService.AtualizarUsuario(usuario);
   try {
       return ResponseEntity.ok(user.get());
   } catch (Exception e) {
    return ResponseEntity.badRequest().build();
}

}

When you search the bank, JPA will know that this guy exists and he will be in a management state and when you pass him to Repository.save he will know that he already exists and will update instead of creating another one.

Browser other questions tagged

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