我们有时候在开发中需要向表中插入自增ID,这个时候领域模型如果想要获取该ID的值,就需要在相应的mapper文件中添加useGeneratedKeys="true" keyProperty="id"。
mapper.xml示例:
<insert id="create" parameterType="payment" useGeneratedKeys="true" keyProperty="id">
insert into payment(serial) values (#{serial})
</insert>
控制层代码:
@PostMapping("/create")
public CommonResult create(Payment payment) {
int result = paymentService.create(payment);
log.info("插入数据的ID:\t" + payment.getId());
log.info("***插入结果:" + result);
if (result > 0) {
return new CommonResult(200, "插入数据成功", result);
} else {
return new CommonResult(444, "插入数据失败", null);
}
}
log信息:
插入数据的ID:4
插入结果:1