適用於 MySQL、PostgreSQL、SQL Server 等支援 VALUES (...), (...), ... 語法的資料庫。
<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 預設 max_allowed_packet=4MB,單條 SQL 不超過 1MB (含參數)。批量筆數需根據行大小估算,建議 500~1000 筆分批。
int insertBatch(List<T> list) → XML collection="list"。int insertBatch(T[] array) → XML collection="array"。int insertBatch(@Param("list") List<T> list, @Param("other") String other) → XML collection="list"。更多 collection 用法參考:MyBatis foreach collection 參數詳解。