From 9bf44c5494372560bfb3cdf1763d881d2815dfcc Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Sun, 31 May 2026 03:21:12 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E6=9B=B4=E6=96=B0=E6=89=B9=E6=AC=A1=E5=86=85=E7=B4=A2?= =?UTF-8?q?=E5=BC=95=E8=AE=A1=E7=AE=97=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 indexInBatch 改为 1-based 计算方式:批次触发条件改为 indexInBatch==batchSize,增强可读性 - 重命名 getUpdateCountsInternal 为 getUpdateCountsOnError,语义更清晰 - 精简方法参数,移除新方案下多余的入参 paramsSize/batchSize/itemIndex - 补充关键变量注释 --- .../xyz/zhouxy/jdbc/JdbcOperationSupport.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/xyz/zhouxy/jdbc/JdbcOperationSupport.java b/src/main/java/xyz/zhouxy/jdbc/JdbcOperationSupport.java index 986c705..295152a 100644 --- a/src/main/java/xyz/zhouxy/jdbc/JdbcOperationSupport.java +++ b/src/main/java/xyz/zhouxy/jdbc/JdbcOperationSupport.java @@ -230,20 +230,26 @@ class JdbcOperationSupport { final BatchUpdateResult result = new BatchUpdateResult(paramsSize, batchCount, batchSize); try (PreparedStatement stmt = conn.prepareStatement(sql)) { + // 表示第几条数据,1, 2, 3, ..., paramsSize int itemIndex = 0; + // 表示第几个批次,0, 1, ..., batchCount-1 int batchIndex = 0; + for (Object[] ps : params) { itemIndex++; fillStatement(stmt, ps); stmt.addBatch(); - final int indexInBatch = itemIndex % batchSize; - if (indexInBatch == 0 || itemIndex >= paramsSize) { + + // 表示当前数据在批次中的索引,1, 2, 3, ..., batchSize-1, batchSize + final int indexInBatch = (itemIndex - 1) % batchSize + 1; + + if (indexInBatch == batchSize || itemIndex == paramsSize) { try { int[] updateCounts = stmt.executeBatch(); result.recordSuccessBatch(batchIndex, updateCounts); } catch (Exception e) { - final int[] updateCounts = getUpdateCountsInternal(paramsSize, batchSize, itemIndex, indexInBatch, e); + final int[] updateCounts = getUpdateCountsOnError(indexInBatch, e); result.recordErrorBatch(batchIndex, updateCounts, e); if (!quietly) { result.interrupt(); @@ -260,18 +266,13 @@ class JdbcOperationSupport { } } - private static int[] getUpdateCountsInternal(final int paramsSize, - final int batchSize, - final int itemIndex, - final int indexInBatch, - final Exception e) { + private static int[] getUpdateCountsOnError(final int indexInBatch, final Exception e) { final int[] updateCounts; if (e instanceof BatchUpdateException) { updateCounts = ((BatchUpdateException) e).getUpdateCounts(); } else { - int n = (itemIndex >= paramsSize && indexInBatch != 0) ? indexInBatch : batchSize; - updateCounts = new int[n]; + updateCounts = new int[indexInBatch]; Arrays.fill(updateCounts, UNKNOWN_COUNT); } return updateCounts;