獲取自增的id,只需要在mybatis配置這個屬性
阿新 • • 發佈:2021-12-20
我們有時候在開發中需要向表中插入自增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>
<insert id="insertDwdTaskInfo" useGeneratedKeys="true" keyProperty="taskId" > insert into mapping_integration.task_info (task_name, db_or_table_id, related_table_info, task_status, task_status_desc, project_name, exec_id, flow, create_person, create_time, finished_time, director) values ( #{taskName}, #{dbOrTableId}, #{relatedTableInfo}, #{taskStatus}, #{taskStatusDesc}, #{projectName}, #{execId}, #{flow}, #{createPerson}, #{createTime}, #{finishedTime}, #{director} ) </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