java spring 带参数的引导实体构造函数不执行
java spring boot Entity constructor with arguments does not execute
我不明白为什么在提供请求主体时调用实体无参数构造函数?如果我删除它并且唯一存在的构造函数是接收参数的构造函数,我会得到预期的输出打印,但我必须实现一个无参数构造函数才能将实体保存在数据库中。
这是请求正文:
{
"str": "stringgg",
"intt": 2,
"doublee": 1.003
}
这是路线:当注释掉空构造函数时,新实例的值匹配请求 json body
@PostMapping("/save")
public List<Modell> obj(@RequestBody Modell model) {
modelRepository.save(model);
System.out.println(model.toString());
return modelRepository.findAll();
}
这是实体 class:
@Table(name = "modelltbl")
@Entity
public class Modell {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private long id;
@Column(name = "str", nullable = true)
private String str;
@Column(name = "intt", nullable = true)
private int intt;
@Column(name = "doublee", nullable = true)
private double doublee;
public Modell(String str, int intt, double doublee)
{
this.str = str;
this.intt = intt;
this.doublee = doublee;
}
public Modell(){}
@Override
public String toString()
{
return String.format("model class,params: %s , %o , %f ", str , intt, doublee);
}
}
首先:不要在控制器级别使用实体。这是糟糕的应用程序设计。
json 将通过 jackson 库进行转换,该库通过调用默认构造函数和属性的 setter 创建对象。如果你不想要这种行为,你可以使用 @JsonCreator
注释。
@JsonCreator
public Modell(@JsonProperty("str")String str, @JsonProperty("intt")int intt, @JsonProperty("doublee")double doublee)
{
this.str = str;
this.intt = intt;
this.doublee = doublee;
}
我不明白为什么在提供请求主体时调用实体无参数构造函数?如果我删除它并且唯一存在的构造函数是接收参数的构造函数,我会得到预期的输出打印,但我必须实现一个无参数构造函数才能将实体保存在数据库中。 这是请求正文:
{
"str": "stringgg",
"intt": 2,
"doublee": 1.003
}
这是路线:当注释掉空构造函数时,新实例的值匹配请求 json body
@PostMapping("/save")
public List<Modell> obj(@RequestBody Modell model) {
modelRepository.save(model);
System.out.println(model.toString());
return modelRepository.findAll();
}
这是实体 class:
@Table(name = "modelltbl")
@Entity
public class Modell {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private long id;
@Column(name = "str", nullable = true)
private String str;
@Column(name = "intt", nullable = true)
private int intt;
@Column(name = "doublee", nullable = true)
private double doublee;
public Modell(String str, int intt, double doublee)
{
this.str = str;
this.intt = intt;
this.doublee = doublee;
}
public Modell(){}
@Override
public String toString()
{
return String.format("model class,params: %s , %o , %f ", str , intt, doublee);
}
}
首先:不要在控制器级别使用实体。这是糟糕的应用程序设计。
json 将通过 jackson 库进行转换,该库通过调用默认构造函数和属性的 setter 创建对象。如果你不想要这种行为,你可以使用 @JsonCreator
注释。
@JsonCreator
public Modell(@JsonProperty("str")String str, @JsonProperty("intt")int intt, @JsonProperty("doublee")double doublee)
{
this.str = str;
this.intt = intt;
this.doublee = doublee;
}