Anderson Martinez
Anderson Martinez

Reputation: 25

how to receive a json object with @RequestBody or @RequestParam

First of all I apologize, I am new using this technology and I really have many doubts. I am trying to send a json object to my controller class, the problem is that with @RequestBody all the data arrives but the foreign keys arrive null. Example enter a new user with the id of a role that already exists in the BD, the user data arrives complete but the role ID arrives null

First I register the data of the role via POST and everything works perfectly with @RequestBody, but when I try to register a user with the role_id that is already saved in the database also using @RequestBody it is saved with the id_rol null

My user entity:

@Entity
public class Usuario implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String correo;
    private String pass;
    private boolean activo;

    @OneToOne(optional = false, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name="rol_id", nullable = false)
    private Rol rol;

public Usuario(){}

public Usuario(String correo, String pass, boolean activo, Rol rol) {
        this.correo = correo;
        this.pass = pass;
        this.activo = activo;
        this.rol = rol;
    }
/*getter y setter*/

My role entity:

@Entity
//@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Rol implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String nombre;
    private boolean activo;

    @OneToMany(mappedBy = "rol")
    private List<Usuario> usuarios;

public Rol(){}

public Rol(String nombre, boolean activo, List<Usuario> usuarios) {
        this.nombre = nombre;
        this.activo = activo;
        this.usuarios = usuarios;
    }
/*getter y setter*/

User Repository:

@Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Serializable> {
    public abstract Usuario findByCorreo(String correo);

}

Role Repository:

public interface RolRepository extends JpaRepository<Rol, Serializable> {
}

User controller class:

@RestController
@RequestMapping("/v1")
public class UsuarioController {

    @Autowired
    UsuarioRepository usuarioRepository;

    @PostMapping("/usuario/add")
    public @ResponseBody ResponseEntity<String> crear(@Valid @RequestBody Usuario usuario) {
        try{
            usuarioRepository.save(usuario);
            return new ResponseEntity<String>("Registro Exitoso..", HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<String>("Ha ocurrido un Error..", HttpStatus.BAD_REQUEST);
        }
    }
}

role controller class:

@RestController
@RequestMapping("/v1")
public class RolController {
    @Autowired
    RolRepository rolRepository;

    @PostMapping("/rol/add")
    public @ResponseBody ResponseEntity<String> crear(@Valid @RequestBody Rol rol) {
        try{
            rolRepository.save(rol);
            return new ResponseEntity<String>("Registro Exitoso..", HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<String>("Ha ocurrido un Error..", HttpStatus.BAD_REQUEST);
        }
    }

}   

This is what I send to my controller:

{
  "correo": "[email protected]",
  "pass": "1234",
  "activo": "true",
  "rol_id": "5"
}

And this is what I receive:

{
  "correo": "[email protected]",
  "pass": "1234",
  "activo": true,
  "rol_id": null
}

How should I receive this body with id_rol = 5? I know that I am doing something wrong in @RequestBody, I appreciate any example you can provide as I have searched and I have not found that. Thank you..!

Upvotes: 1

Views: 4208

Answers (1)

VadymVL
VadymVL

Reputation: 5566

This is because you are sending a wrong JSON structure to your REST Controller.

In your Usuario class, the role_id is actually an object field with a name rol which represents Rol class. So you need to pass Rol with id as an JSON object in your request:

{
  "correo": "[email protected]",
  "pass": "1234",
  "activo": "true",
  "rol": {
    "id":"5"
  }
}

Upvotes: 1

Related Questions