專案使用 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)
...
public interface PrintMapper {
@InsertProvider(type = PrintMapperProvider.class, method = "insertAllLotWithVehicleCode4H2")
void insertAllLotWithVehicleCode(List<LotWithVehicleCodeBO> lotWithVehicleCodes);
}
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 nf = NumberFormat.getInstance(Locale.US);
nf.setGroupingUsed(false); // 關鍵:關閉分組分隔符
MessageFormat mf = new MessageFormat("...");
mf.setFormatByArgumentIndex(0, nf); // 索引 0 套用此格式
避免 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 風險、程式碼更直觀。
max_allowed_packet、SQL Server 65536*網路封包),建議每 500~1000 筆分批執行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 在開發/測試環境(資料量小)極難復現,上線後才爆發,屬於典型的「隱性國際化缺陷」。