refactor: 优化批量更新批次内索引计算逻辑

- 将 indexInBatch 改为 1-based 计算方式:批次触发条件改为 indexInBatch==batchSize,增强可读性
- 重命名 getUpdateCountsInternal 为 getUpdateCountsOnError,语义更清晰
- 精简方法参数,移除新方案下多余的入参 paramsSize/batchSize/itemIndex
- 补充关键变量注释
This commit is contained in:
2026-05-31 03:21:12 +08:00
parent a51fcef845
commit 9bf44c5494

View File

@@ -230,20 +230,26 @@ class JdbcOperationSupport {
final BatchUpdateResult result = new BatchUpdateResult(paramsSize, batchCount, batchSize); final BatchUpdateResult result = new BatchUpdateResult(paramsSize, batchCount, batchSize);
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
// 表示第几条数据1, 2, 3, ..., paramsSize
int itemIndex = 0; int itemIndex = 0;
// 表示第几个批次0, 1, ..., batchCount-1
int batchIndex = 0; int batchIndex = 0;
for (Object[] ps : params) { for (Object[] ps : params) {
itemIndex++; itemIndex++;
fillStatement(stmt, ps); fillStatement(stmt, ps);
stmt.addBatch(); 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 { try {
int[] updateCounts = stmt.executeBatch(); int[] updateCounts = stmt.executeBatch();
result.recordSuccessBatch(batchIndex, updateCounts); result.recordSuccessBatch(batchIndex, updateCounts);
} }
catch (Exception e) { catch (Exception e) {
final int[] updateCounts = getUpdateCountsInternal(paramsSize, batchSize, itemIndex, indexInBatch, e); final int[] updateCounts = getUpdateCountsOnError(indexInBatch, e);
result.recordErrorBatch(batchIndex, updateCounts, e); result.recordErrorBatch(batchIndex, updateCounts, e);
if (!quietly) { if (!quietly) {
result.interrupt(); result.interrupt();
@@ -260,18 +266,13 @@ class JdbcOperationSupport {
} }
} }
private static int[] getUpdateCountsInternal(final int paramsSize, private static int[] getUpdateCountsOnError(final int indexInBatch, final Exception e) {
final int batchSize,
final int itemIndex,
final int indexInBatch,
final Exception e) {
final int[] updateCounts; final int[] updateCounts;
if (e instanceof BatchUpdateException) { if (e instanceof BatchUpdateException) {
updateCounts = ((BatchUpdateException) e).getUpdateCounts(); updateCounts = ((BatchUpdateException) e).getUpdateCounts();
} }
else { else {
int n = (itemIndex >= paramsSize && indexInBatch != 0) ? indexInBatch : batchSize; updateCounts = new int[indexInBatch];
updateCounts = new int[n];
Arrays.fill(updateCounts, UNKNOWN_COUNT); Arrays.fill(updateCounts, UNKNOWN_COUNT);
} }
return updateCounts; return updateCounts;