mybaits返回自增主鍵ID
阿新 • • 發佈:2019-02-12
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之後已經支援批量插入並獲取自增主鍵值了。