Spring Data JPA JpaRepository only uses No Arg Constructor



我有一个简单的REST API,它是用Spring Boot创建的。

在这个应用程序中,我有一个名为"费用"的POJO,其中包含4个字段。我有一个无参数构造函数和另一个只接受两个输入的构造函数。一个字符串值"项目"和一个整数值"金额"。 日期是使用 LocalData.now(( 方法设置的,id 是在服务器运行的 MySql 数据库中自动设置的。

这是我的实体类

@Entity
public class Expense {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Integer id;
private String date;
private String item;
private Integer amount;
//No Arg Construction required by JPA
public Expense() {
}
public Expense(String item, Integer amount) {
this.date = LocalDate.now().toString();
this.item = item;
this.amount = amount;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
}

我还有另一个带有 RestController 注释的类,其中我设置了一个使用请求映射注释的发布方法发布费用对象的方法。

@RestController
public class ExpController {
private ExpService expService;
private ExpenseRepo expenseRepo;
@Autowired
public ExpController(ExpService expService, ExpenseRepo expenseRepo) {
this.expService = expService;
this.expenseRepo = expenseRepo;
}

@RequestMapping(path = "/addExp", method=RequestMethod.POST)
public void addExp(Expense expense){
expenseRepo.save(expense);
}    
}

现在我终于使用PostMan来发出HTTP Post请求了。我制作了一个简单的 Json 格式文本来发送项目和金额

{
"item":"Bread",
"amount": 75
}

发出 post 请求后,我只能看到创建了一个新条目,但所有值都设置为 null。

我做了一些实验,发现 expenseRepo.save(expense( 方法仅使用默认的 no Arg 构造函数来保存数据。但它没有使用第二个构造函数来获取我通过 Postman 传递的两个参数

如何解决这个问题。请帮忙

像这样更改控制器方法

@RequestMapping(path = "/addExp", method=RequestMethod.POST)
public void addExp(@RequestBody Expense expense){
expenseRepo.save(expense);
}   

您需要使用@RequestBody

相关内容

最新更新