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

MyBatis 批量刪除最佳實踐:foreach 標籤動態構建 IN 條件

     編輯:Java 相關知識

MyBatis 中批量刪除的標準寫法:利用 <foreach> 標籤遍歷集合/數組,動態拼接 IN (...) 條件。本文詳細解析屬性含義、參數傳遞方式(List/Array/Map)與常見坑點。

核心 Mapper XML

<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>

foreach 關鍵屬性詳解

屬性含義示例值
collection要遍歷的集合鍵名。傳 List 時為 list,傳 Array 時為 array,傳 Map 時為 Map 的 keylist / array / ids
item遍歷時每個元素的別名,供 #{...} 使用standardId
index索引別名(List 為索引,Map 為 key),可選idx
open遍歷開始前的前綴字符串(
separator元素間分隔符,
close遍歷結束後的後綴字符串)

三種參數傳遞方式

1. 直接傳 List

// Mapper
void deleteByIds(List<Integer> ids);

// Service
mapper.deleteByIds(Arrays.asList(1,2,3,4,5));
// XML: collection="list"

2. 直接傳數組

// Mapper
void deleteByIds(Integer[] ids);

// Service
mapper.deleteByIds(new Integer[]{1,2,3});
// XML: collection="array"

3. 傳 Map(多參數時必須)

// 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)

常見坑點與最佳實踐

  1. 空集合防護:MyBatis 3.2+ 自動處理空集合(生成 IN (NULL) 導致不匹配),但建議 Service 層預判空集合直接返回 0
  2. 大批量分批:單條 SQL IN 參數過多(超過 1000)可能導致解析慢/超限,建議 Service 層分批(如每 500 條)循環調用
  3. jdbcType 指定:#{id, jdbcType=INTEGER} 避免類型推斷問題,尤其針對 Oracle
  4. 主鍵回填:批量刪除無需回填主鍵,useGeneratedKeys 設為 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 批量操作的核心技能。

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