MyBatis在insert插入操作時返回主鍵ID的配置
阿新 • • 發佈:2018-12-29
很多時候,在向資料庫插入資料時,需要保留插入資料的id,以便進行後續的update操作或者將id存入其他表作為外來鍵。
但是,在預設情況下,insert操作返回的是一個int值,並且不是表示主鍵id,而是表示當前SQL語句影響的行數。。。
接下來,我們看看MyBatis如何在使用MySQL和Oracle做insert插入操作時將返回的id繫結到物件中。
MySQL用法:
<insert id="insert" parameterType="com.test.User" keyProperty="userId" useGeneratedKeys="true" >
上面配置中,“keyProperty”表示返回的id要儲存到物件的那個屬性中,“useGeneratedKeys”表示主鍵id為自增長模式。
MySQL中做以上配置就OK了,較為簡單,不再贅述。
<insert id="insert" parameterType="com.test.User"> <selectKey resultType="INTEGER" order="BEFORE" keyProperty="userId"> SELECT SEQ_USER.NEXTVAL as userId from DUAL </selectKey> insert into user (user_id, user_name, modified, state) values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{modified,jdbcType=TIMESTAMP}, #{state,jdbcType=INTEGER}) </insert>