I have an object which gets two parameters through a json POST request to create a new entry in the database and I get this error:
"Type definition error: [simple type, class ffuentese.rest_example.Persona]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of
ffuentese.rest_example.Persona
(no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 2, column: 3]",
This is the object:
@Entity
public class Persona {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String nombre;
private String apellido;
public Persona(String nombre, String apellido) {
this.nombre = nombre;
this.apellido = apellido;
}
public Integer getId() {
return id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
}
This is the controller method:
@PostMapping(path="/persona")
public @ResponseBody String addPersona(@RequestBody Persona p) {
personaRepository.save(p);
return "success";
}
Spring Boot Error Handler Let's explore some Spring annotations used to handle exceptions. RestController is the base annotation for classes that handle REST operations. ExceptionHandler is a Spring annotation that provides a mechanism to treat exceptions thrown during execution of handlers (controller operations).
The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.
You have to provide implementation to use your error handler, map the response to response entity and throw the exception. Create new error exception class with ResponseEntity field. Custom error handler which maps the error response back to ResponseEntity.
You'll need an empty constructor to allow for Jackson to perform it's deserialization actions correctly.
Moreover though, using the entity model as a data transfer object is not a good idea. I would suggest to create a PersonaDto
which will contain all the fields you'll require to construct for object and the use a Spring converter
to convert it over to a Persona
object.
This way you'll be more flexible and you'll not be binding you transfer objects to the actual entity models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With