Mybatis 在 insert 之后想获取自增的主键 id的正确方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huangyaa729/article/details/83618510

今天在调试代码时,碰到了莫名其妙的问题,最后还是单步调试时,发现在使用mybatis的insert操作时,返回的值一直是“1”,跟我想象的有些出入,一直以为返回的应该是插入时的id值;

Mybatis生成insert接口的用法正解:

<insert id="insert"
        parameterType="user">
    INSERT INTO `user` (`name`,sex,register_ts) VALUES (#{name},#{sex},#{registerTs})
    <selectKey resultType="int" keyProperty="id" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>
</insert>
  1. 返回的1是影响的行数,并不是自增的主键id;

  2. 想要获取自增主键id,需要通过xx.getId()方法获取,因为在mybatis中指定自增主键id封装到了对象的属性中,所以我们需要在对象中来获取

猜你喜欢

转载自blog.csdn.net/huangyaa729/article/details/83618510