方式一:LAST_INSERT_ID()

  • keyProperty:将查询到的主键值设置到parameterType指定对象的哪个属性。
  • order: 标签内的sql语句相对于insert语句的执行顺序,AFTER表示select LAST_INSERT_ID() 这个语句将在insert语句之后执行。
<insert id="insertUser" parameterType="com.danny.mybatis.po.User">
        <selectKey keyProperty="userId" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into T_USER(userName,birthday,sex,address) values (#{userName},#{birthday},#{sex},#{address})
 </insert>

方式二:useGeneratedKeys

注意:适用于MySQL等支持逐渐自增的数据库;

<insert id="add" parameterType="class" useGeneratedKeys="true" keyProperty="id">    <!--如果实体类中的ID和数据库中的ID名称不一致还需加上keyProperty="userId" 用来指定实体类中的ID名称-->
  insert into ....
</insert>

insert返回主键值

参考:

  1. https://www.cnblogs.com/fsjohnhuang/p/4078659.html;

相关文章: