萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MS SQL 資料庫

MyBatis MapperProvider MessageFormat 千位數分隔符導致批次SQL解析失效之根因與修正

問題情境:批次插入突發 BuilderException

專案使用 MyBatis @InsertProvider 動態構建批次 INSERT 語句,上線初期正常,業務量激增至單次 500+ 筆資料時,開始拋出:

org.apache.ibatis.builder.BuilderException: Improper inline parameter map format. Should be: #{propName,attr1=val1,attr2=val2}
    at org.apache.ibatis.builder.SqlSourceBuilder$ParameterMappingTokenHandler.buildParameterMapping(SqlSourceBuilder.java:89)
    ...

代碼還原

Mapper 介面

public interface PrintMapper {
    @InsertProvider(type = PrintMapperProvider.class, method = "insertAllLotWithVehicleCode4H2")
    void insertAllLotWithVehicleCode(List<LotWithVehicleCodeBO> lotWithVehicleCodes);
}

Provider 實作(問題核心)

public String insertAllLotWithVehicleCode4H2(Map<String, List<LotWithVehicleCodeBO>> map) {
    List<LotWithVehicleCodeBO> list = map.get("list");
    StringBuilder sb = new StringBuilder("INSERT INTO MTC_LOT_WITH_VEHICLE_CODE (LOT_CODE, PRODUCT_VEHICLE_CODE) VALUES ");
    
    // 關鍵問題行:MessageFormat 預設使用 Locale 格式化數字
    MessageFormat messageFormat = new MessageFormat(
        "(#'{'list[{0}].lotCode}, #'{'list[{0}].productVehicleCode})");
    
    int size = list.size();
    for (int i = 0; i < size; i++) {
        sb.append(messageFormat.format(new Object[]{i})); // i 為 Integer
        if (i < size - 1) sb.append(",");
    }
    return sb.toString();
}

根因深度剖析

MessageFormat.format() 內部使用 NumberFormat.getInstance(Locale.getDefault()) 格式化數值。當 i >= 1000 時,預設 Locale(如 Locale.US、Locale.TAIWAN)會加入千位數分隔符(預設為逗號 ,):

i = 1000  →  格式化後字串 "1,000"
i = 1234  →  "1,234"

導致產生的 SQL 片段變為:

(#{list[1,000].lotCode}, #{list[1,000].productVehicleCode})

MyBatis 解析器遇到 #{list[1,000]... 時,誤以為逗號後為參數屬性(如 #{prop,attr=val}),因而拋出 Improper inline parameter map format。

解決方案:三種修正方式

方案一:字串化數字(最簡單、相容性最好)

// 將 i 轉為 String,MessageFormat 視為字串不加分隔符
sb.append(messageFormat.format(new Object[]{String.valueOf(i)}));

或簡寫:new Object[]{i + ""} / new Object[]{Integer.toString(i)}。

方案二:指定無分隔符的 NumberFormat

NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setGroupingUsed(false); // 關鍵:關閉分組分隔符
MessageFormat mf = new MessageFormat("...");
mf.setFormatByArgumentIndex(0, nf); // 索引 0 套用此格式

方案三:改用 String.format / StringBuilder 直接拼接(推薦)

避免 MessageFormat 額外開銷與 Locale 陷阱:

public String insertAllLotWithVehicleCode4H2(Map<String, List<LotWithVehicleCodeBO>> map) {
    List<LotWithVehicleCodeBO> list = map.get("list");
    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO MTC_LOT_WITH_VEHICLE_CODE (LOT_CODE, PRODUCT_VEHICLE_CODE) VALUES ");
    
    for (int i = 0; i < list.size(); i++) {
        if (i > 0) sb.append(",");
        sb.append("(#{'list[").append(i).append("].lotCode}, #{'list[").append(i).append("].productVehicleCode})");
    }
    return sb.toString();
}

效能更佳、零 Locale 風險、程式碼更直觀。

延伸建議:大批次插入的效能優化

  • 分批次:單次 SQL 過長會超過資料庫封包限制(MySQL max_allowed_packet、SQL Server 65536*網路封包),建議每 500~1000 筆分批執行
  • 使用 MyBatis 內建 foreach:XML 映射檔寫法更簡潔、可維護性高
  • <insert id="batchInsert" parameterType="java.util.List">
      INSERT INTO MTC_LOT_WITH_VEHICLE_CODE (LOT_CODE, PRODUCT_VEHICLE_CODE) VALUES
      <foreach collection="list" item="item" index="index" separator=",">
        (#{item.lotCode}, #{item.productVehicleCode})
      </foreach>
    </insert>
  • 資料庫層面:目標表適當調大 bulk_insert_buffer_size、使用最小記錄模式(簡單復原模式 + TABLOCK)

核心教訓:任何涉及數字格式化的國際化敏感操作,務必明確指定 Locale 或改用非格式化拼接。這類 Bug 在開發/測試環境(資料量小)極難復現,上線後才爆發,屬於典型的「隱性國際化缺陷」。

copyright © 萬盛學電腦網 all rights reserved