我不明白為什么在提供請求正文時呼叫物體無引數建構式?如果我洗掉它并且唯一存在的建構式是接收引數的建構式,我會得到預期的輸出列印,但我必須實作一個無引數建構式才能將物體保存在資料庫中。這是請求正文:
{
"str": "stringgg",
"intt": 2,
"doublee": 1.003
}
這是路線:注釋掉空建構式時,新實體的值與請求json正文匹配
@PostMapping("/save")
public List<Modell> obj(@RequestBody Modell model) {
modelRepository.save(model);
System.out.println(model.toString());
return modelRepository.findAll();
}
這是物體類:
@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);
}
}
uj5u.com熱心網友回復:
首先:不要在控制器級別使用物體。這是糟糕的應用程式設計。
json 將通過 jackson 庫進行轉換,該庫通過呼叫默認建構式和屬性的設定器來創建物件。如果您不想要這種行為,您可以使用@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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435146.html
