mybaits返回自增主键ID

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 07:05   11   0

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之后已经支持批量插入并获取自增主键值了。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP