Spring数据JPA JPA仅使用无参数构造函数
我有一个用Spring Boot创建的简单RESTAPI 在这个应用程序中,我有一个名为Expense的POJO,有4个字段。我有一个无参数构造函数和另一个只接受两个输入的构造函数。一个字符串值“item”和一个整数值“amount”。日期是使用LocalData.now()方法设置的,id是在服务器上运行的MySql数据库中自动设置的 这是我的实体类Spring数据JPA JPA仅使用无参数构造函数,spring,rest,spring-boot,Spring,Rest,Spring Boot,我有一个用Spring Boot创建的简单RESTAPI 在这个应用程序中,我有一个名为Expense的POJO,有4个字段。我有一个无参数构造函数和另一个只接受两个输入的构造函数。一个字符串值“item”和一个整数值“amount”。日期是使用LocalData.now()方法设置的,id是在服务器上运行的MySql数据库中自动设置的 这是我的实体类 @Entity public class Expense { @Id @GeneratedValue (strategy = G
@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注释的类,在这个类中,我使用请求映射注释设置了一个post方法来post费用对象
@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)方法只使用默认的无参数构造函数来保存数据。但它并没有使用第二个构造函数,该构造函数接受我通过Postman传递的两个参数
如何解决这个问题。请帮助像这样更改控制器方法
@RequestMapping(path = "/addExp", method=RequestMethod.POST)
public void addExp(@RequestBody Expense expense){
expenseRepo.save(expense);
}
您需要使用
@RequestBody
哇,谢谢。这真的奏效了。只有一个问题,日期设置为空。我再次发现JpaRepository使用的是no-Arg构造函数。我已经在no arg构造函数主体中设置了LocalDate.now()方法,现在它正在更新日期。有没有一种方法可以指示SpringBoot强制使用第二个构造器?你在混合两种东西。1.当您从邮递员发送数据并在控制器中接收数据时,SpringData/JpaRepository根本不会出现在画面中。2.只有当您调用expenseRepo.save(费用)时,spring数据才会出现在图片中代码>。在这一点上进行调试,看看日期是否为空。3.我不相信spring会在调用API时调用构造函数来设置类的值。它使用反射并直接设置值。所以,一旦您在控制器中接收到费用对象。调用expense.setDate(…)
而不是在控制器中进行设置。