Java Spring:使用 REST 服务发布新对象时出现类型定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51014320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:55:12  来源:igfitidea点击:

Spring: Type definition error when posting a new object using a REST service

javaspringrest

提问by ffuentes

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:

我有一个对象,它通过 json POST 请求获取两个参数以在数据库中创建一个新条目,但出现此错误:

"Type definition error: [simple type, class ffuentese.rest_example.Persona]; nested exception is com.fasterxml.Hymanson.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]",

“类型定义错误:[简单类型,类 ffuentese.rest_example.Persona];嵌套异常是 com.fasterxml.Hymanson.databind.exc.InvalidDefinitionException:无法构造实例ffuentese.rest_example.Persona(没有创建者,如默认构造,存在):无法反序列化[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";

}

采纳答案by akortex91

You'll need an empty constructor to allow for Hymanson to perform it's deserialization actions correctly.

您将需要一个空的构造函数以允许 Hymanson 正确执行它的反序列化操作。

Moreover though, using the entity model as a data transfer object is not a good idea. I would suggest to create a PersonaDtowhich will contain all the fields you'll require to construct for object and the use a Spring converterto convert it over to a Personaobject.

此外,使用实体模型作为数据传输对象并不是一个好主意。我建议创建一个PersonaDto包含您需要为对象构造的所有字段并使用 Springconverter将其转换为对象的字段Persona

This way you'll be more flexible and you'll not be binding you transfer objects to the actual entity models.

这样,您将更加灵活,并且不会绑定您将对象传输到实际实体模型。