---
title: " Spring ibatis批处理"
author: "oyprunner"
date: "2009-12-15T18:05:32Z"
tags: []
categories: ["企业架构"]
slug: "spring-ibatis"
draft: false
lastmod: "2010-07-26T12:39:02Z"
id: 549134
url: "https://oyprunner.iteye.com/blog/549134"
---

Spring ibatis批处理 \[b] 方法一\[/b] \[code="java"](1)spring模式:尽管spring已经配置了事务,但以下代码中还是要设置事务,不然batch不会起作用;另外这里虽然设了一下事务处理,但对 全局事务并不会造成影响; 注:不启用事务将建立多次连接,这表示batch没起作用,建立事务后一次连接就搞定了. public void batchAddExamlog(List examlogList) throws SQLException{ SqlMapClient smc=this.getSqlMapClient(); try { smc.startTransaction(); smc.startBatch(); for (Iterator iter = examlogList.iterator(); iter.hasNext();) { Examlog log = (Examlog) iter.next(); smc.update("insertExamlog", log); } smc.executeBatch(); } catch (Exception e) { // TODO: handle exception }finally{ smc.commitTransaction(); smc.endTransaction(); } \[/code] \[b]方法二\[/b] \[code="java"]2直接采用回调函数设置 public void batchAddExamlog2(List examlogList){ getSqlMapClientTemplate().execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { executor.startBatch(); executor.update //("insertSomething", "myParamValue"); executor.update("insertSomethingElse", "myOtherParamValue");//出错所有回滚 executor.executeBatch(); return null; } }); }\[/code] Spring+ibatis批量处理心得3 到一个这东西都写到3了，针对上回说到30000条数据的批量插入工作。30000条数据的批量插入在一个事务里处理固然是快，但是这只是测试环境，30000条数据在数据库的缓存里必然对数数据库的缓存和锁数量都是一个大的挑战，固在新的程序中我们使用了分批事务提交的方式，这样为了保持数据的正确行就只能人为控制数据库中已被插入的数据是否delete掉。另外，使用Batch块提交会引发一个问题就是，如果batch块中发生了异常，我们得不到异常数据的行号即任何信息，所以只能是鱼和熊掌不可兼得（我已关注过insert方法中返回pk的方法了，但好像在batch中他反回不了出错的行号，也许是我没有找到方法，如有人有好方法请共享一下，在这里表示感谢），大家酌情考虑吧，只能到到自己需要的平衡点了。 建议：如果对数据的准确性毋庸置疑的话就是用batch处理。如果不能确定准确性的话，如果对那条数据出错无所谓的话就也可以用batch，但是非要返回出错行号的话就不要用batch了，直接在外面套用一个事务，然后try catch一下，处理一下行号。