已有包含16500条数据的List,无法一次性提交到MySQL,因为已超过MySQL的max_allowed_packet故考虑每1000条提交一次,最先想到的是16500 / 1000 = 16,然后定义int start、int end根据start、end不断获取该List的subList,然后再逐个提交subList。但是总觉得这种方式不够好,前辈们如果遇到这种情况会想要怎么解决呢?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
这是基于ibatis batch insert的代码,从项目中抠出来的,希望能对你有所帮助
protected <E> boolean executeBatch(List<E> elist, String sqlId) throws SQLException {
boolean isAutoCommit = true;
SqlMapClient sqlMapClient = this.getSqlMapClient();
try {
sqlMapClient.startTransaction();
sqlMapClient.startBatch();
isAutoCommit = sqlMapClient.getCurrentConnection().getAutoCommit();
sqlMapClient.getCurrentConnection().setAutoCommit(false);
int flag = 0;
for (int i = 0, size = elist.size(); i < size; ++i) {
sqlMapClient.insert(sqlId, elist.get(i));
if (++flag == 200) {
flag = 0;
sqlMapClient.executeBatch();
}
}
sqlMapClient.executeBatch();
sqlMapClient.commitTransaction();
} catch (SQLException e) {
sqlMapClient.getCurrentConnection().rollback();// 事务回滚
throw new SQLException(e.getCause());
} finally {
sqlMapClient.getCurrentConnection().setAutoCommit(isAutoCommit);// 恢复原来的状态
sqlMapClient.endTransaction();
}
return true;
}