首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

MyBatis 批量插入通用寫法:foreach 拼接 VALUES 多值列表

     編輯:Java 綜合教學

MyBatis 批量插入通用寫法

適用於 MySQL、PostgreSQL、SQL Server 等支援 VALUES (...), (...), ... 語法的資料庫。

Mapper XML 範例

<mapper namespace="com.xxx.mapper.XXXRecordMapper">
  <resultMap id="BaseResultMap" type="com.xxx.model.XXXRecord">
    <id column="AutoId" property="autoid" jdbcType="BIGINT"/>
    <result column="UserId" property="userid" jdbcType="BIGINT"/>
    <result column="NoticedTime" property="noticedtime" jdbcType="TIMESTAMP"/>
  </resultMap>

  <sql id="Base_Column_List">AutoId, UserId, NoticedTime</sql>

  <!-- 批量插入 -->
  <insert id="insertBatch" parameterType="java.util.List">
    INSERT INTO T_XXXRecord (AutoId, UserId, NoticedTime) VALUES
    <foreach collection="list" item="item" index="index" separator=",">
      (#{item.autoid,jdbcType=BIGINT},
       #{item.userid,jdbcType=BIGINT},
       #{item.noticedtime,jdbcType=TIMESTAMP})
    </foreach>
  </insert>
</mapper>

關鍵屬性說明

屬性說明
collection集合參數名稱:單參數 List 固定為 list;單參數陣列為 array;多參數時需封裝 Map,值為 Map 的 key。
item迭代變數名,對應集合中單個元素 (如上例的 item 代表 XXXRecord 物件)。
index索引變數名 (可選),List 為索引值,Map 為 key。
separator分隔符,多值列表間用逗號 "," 分隔。
open/close可選,整個 foreach 輸出內容的前綴/後綴 (如 open="(" close=")")。

MySQL 限制提醒

MySQL 預設 max_allowed_packet=4MB,單條 SQL 不超過 1MB (含參數)。批量筆數需根據行大小估算,建議 500~1000 筆分批。

參數傳遞變體

  • List 參數: 介面 int insertBatch(List<T> list) → XML collection="list"。
  • 陣列參數: 介面 int insertBatch(T[] array) → XML collection="array"。
  • 多參數 (Map): 介面 int insertBatch(@Param("list") List<T> list, @Param("other") String other) → XML collection="list"。

更多 collection 用法參考:MyBatis foreach collection 參數詳解。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved