(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();
- }
- }
(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;
- }
- });
- }