mybatis中配置useGeneratedKeys="true" keyProperty="id" 的作用

我们有时候在开发中需要向表中插入自增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
发布了38 篇原创文章 · 获赞 4 · 访问量 3174

猜你喜欢

转载自blog.csdn.net/qq_42107430/article/details/104682308