1. 程式人生 > >Mybatis+Mysql 批量插入的時候返回主鍵ID

Mybatis+Mysql 批量插入的時候返回主鍵ID

<insert id="insertAlarmLinkmanList" useGeneratedKeys="true" keyProperty="alarmLinkmanId" >
  insert into alarm_linkman (user_name, project_id, 
  project_name, phone, email, status)
  values
  <foreach collection="list" item="item" index="index" separator=",">
    (#{item.userName,jdbcType=VARCHAR}, #{item.projectId,jdbcType=INTEGER}, 
     #{item.projectName,jdbcType=VARCHAR}, #{item.phone,jdbcType=VARCHAR}, #{item.email,jdbcType=VARCHAR}, 
     #{item.status,jdbcType=INTEGER})
  </foreach>
</insert>

useGeneratedKeys:
設定是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設定的領域模型屬性中。MySQL和SQLServer執行auto-generated key field,
因此當資料庫設定好自增長主鍵後,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支援auto-generated key field的資料庫就不能用這種方法獲取主鍵了
keyProperty:
返回主鍵ID到Javabean的屬性名稱

注意:我在這裡做的批量插入,傳入的是一個List集合,所以<foreach>的collection屬性要寫list,插入完成後會直接把主鍵ID放入你的Javabean中。最重要的是這種寫法只能是
Mybatis版本3.3.1以上,不然會報錯。資料庫要mysql(其他資料庫沒試過)