【发布时间】:2018-06-18 12:39:36
【问题描述】:
我有这个使用 Spring Boot 创建的简单 REST API。
在这个应用程序中,我有一个名为 Expense 的 POJO,它有 4 个字段。我有一个无参数构造函数和另一个只接受两个输入的构造函数。一个字符串值“item”和一个整数值“amount”。使用 LocalData.now() 方法设置日期,并在服务器中运行的 MySql db 中自动设置 ID。
这是我的实体类
@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 方法发布 Expense 对象。
@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 传递的两个参数
如何解决这个问题。请帮忙
【问题讨论】:
标签: spring rest spring-boot