mybaits返回自增主键ID

mybaits两种获取自增主键ID的方法:一种是使用useGeneratedKeys,第二种是selectKey方法获取。

useGeneratedKeys

<insert id="insert" parameterType="com.github.chengbin.auth.entity.User" useGeneratedKeys="true" keyProperty="id">
    insert into sys_users (id, username, password, 
      salt, locked)
    values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{salt,jdbcType=VARCHAR}, #{locked,jdbcType=BIT})
  </insert>

selectKey

<insert id="insert" parameterType="com.github.chengbin.auth.entity.User" >
    <selectKey keyProperty="id" resultType="int">
      select LAST_INSERT_ID()
    </selectKey>
    insert into sys_users (id, username, password,
      salt, locked)
    values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{salt,jdbcType=VARCHAR}, #{locked,jdbcType=BIT})
  </insert>

前提是数据库表主键是自增长的。获取主键ID也比较简单,user.getId()即可获取。它会自动把自增长主键ID设置到属性ID里面返回。MyBatis3.4.0之后已经支持批量插入并获取自增主键值了。

原文地址:https://www.cnblogs.com/dand/p/10514623.html