MyBatis 中批量刪除的標準寫法:利用 <foreach> 標籤遍歷集合/數組,動態拼接 IN (...) 條件。本文詳細解析屬性含義、參數傳遞方式(List/Array/Map)與常見坑點。
<delete id="deleteByStandardIds">
delete from t_standard_catalog
where standard_id in
<foreach collection="array" item="standardId" open="(" close=")" separator=",">
#{standardId, jdbcType=INTEGER}
</foreach>
</delete>
<delete id="deleteByStandardIds" parameterType="java.util.List">
delete from t_standard_catalog
where standard_id in
<foreach collection="list" item="standardId" open="(" close=")" separator=",">
#{standardId, jdbcType=INTEGER}
</foreach>
</delete>
| 屬性 | 含義 | 示例值 |
|---|---|---|
collection | 要遍歷的集合鍵名。傳 List 時為 list,傳 Array 時為 array,傳 Map 時為 Map 的 key | list / array / ids |
item | 遍歷時每個元素的別名,供 #{...} 使用 | standardId |
index | 索引別名(List 為索引,Map 為 key),可選 | idx |
open | 遍歷開始前的前綴字符串 | ( |
separator | 元素間分隔符 | , |
close | 遍歷結束後的後綴字符串 | ) |
// Mapper
void deleteByIds(List<Integer> ids);
// Service
mapper.deleteByIds(Arrays.asList(1,2,3,4,5));
// XML: collection="list"
// Mapper
void deleteByIds(Integer[] ids);
// Service
mapper.deleteByIds(new Integer[]{1,2,3});
// XML: collection="array"
// Mapper
void deleteByIds(@Param("ids") List<Integer> ids, @Param("type") String type);
// Service
Map<String, Object> params = new HashMap<>();
params.put("ids", Arrays.asList(1,2,3));
params.put("type", "A");
mapper.deleteByIds(params);
// XML: collection="ids" (對應 @Param 值或 Map key)
IN (NULL) 導致不匹配),但建議 Service 層預判空集合直接返回 0IN 參數過多(超過 1000)可能導致解析慢/超限,建議 Service 層分批(如每 500 條)循環調用#{id, jdbcType=INTEGER} 避免類型推斷問題,尤其針對 OracleuseGeneratedKeys 設為 false<insert id="batchInsert">
insert into t_user (name, age) values
<foreach collection="list" item="user" separator=",">
(#{user.name}, #{user.age})
</foreach>
</insert>
掌握 foreach 靈活運用,是 MyBatis 批量操作的核心技能。