gpt4 book ai didi

spring - 错误处理 Spring JdbcTemplate batchUpdate

转载 作者:行者123 更新时间:2023-12-01 04:54:16 25 4
gpt4 key购买 nike

我正在尝试使用 batchUpdate 更新表中的数千行。我的要求是:

1) 假设一个批次有 1000 条记录。记录号 235 导致了错误。如何找出导致错误的记录。

2) 假设记录 600 没有导致更新(原因可能是没有与 where 子句匹配的记录)。如何找出未导致更新的记录。

3)在上述两种情况下,我如何继续处理剩余的记录。

最佳答案

经过长时间的搜索和调试,唯一的解决方案是转到 BatchUpdateException 类并找到负元素并从 MAP 中推断出错误的插入值。

import java.sql.BatchUpdateException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;


import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Repository("dao_")
public class YouDao extends CommunDao implements IyouDao {

public void bulkInsert(final List<Map<String, String>> map)
throws BusinessException {
try {

String sql = " insert into your_table " + "( aa,bb )"
+ "values " + "( ?,? )";
BatchPreparedStatementSetter batchPreparedStatementSetter = new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i)
throws SQLException {
Map<String, String> bean = map.get(i);

ps.setString(1, bean.get("aa"));
ps.setString(2, bean.get("bb"));
//..
//..

}

@Override
public int getBatchSize() {
return map.size();
}
};

getJdbcTemplate().batchUpdate(sql, batchPreparedStatementSetter);

}

catch (Exception e) {
if (e.getCause() instanceof BatchUpdateException) {
BatchUpdateException be = (BatchUpdateException) e.getCause();
int[] batchRes = be.getUpdateCounts();
if (batchRes != null && batchRes.length > 0) {
for (int index = 0; index < batchRes.length; index++) {
if (batchRes[index] == Statement.EXECUTE_FAILED) {
logger.error("Error execution >>>>>>>>>>>"
+ index + " --- , codeFail : " + batchRes[index]
+ "---, line " + map.get(index));
}
}
}
}
throw new BusinessException(e);
}

}

}

关于spring - 错误处理 Spring JdbcTemplate batchUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38615358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com