1. 程式人生 > >mybatis的insert元素屬性詳解 及 在insert插入資料獲取主鍵id的值

mybatis的insert元素屬性詳解 及 在insert插入資料獲取主鍵id的值

很多時候,在向資料庫插入資料時,需要保留插入資料的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了,較為簡單,不再贅述。

Oracle用法:

複製程式碼
<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>
複製程式碼

Oracle用法中,需要注意的是:由於Oracle沒有自增長一說法,只有序列這種模仿自增的形式,所以不能再使用“useGeneratedKeys”屬性。

而是使用<selectKey>將ID獲取並賦值到物件的屬性中,insert插入操作時正常插入id。