ibatis 批量更新与事务

public int addMessages(List list) {
    int result = 0;
    try { 
        this.getSqlMapTransactionManager().startTransaction();
        this.startBatch();
        for(int i=0;i<list.size();i++) {
              this.insert("addMessage",(Message)list.get(i));
        }
        this.executeBatch();
        this.getSqlMapTransactionManager().commitTransaction();
        result = 1;
   } catch (Exception e) {
        result = 0;
       e.printStackTrace();
  } finally {
   try {
          this.getSqlMapTransactionManager().endTransaction();
    } catch (Exception e) {
          e.printStackTrace();
    }
          return result;
   }
}
这样就会报错

com.ibatis.common.jdbc.exception.NestedSQLException: Could not start transaction.  Cause: com.ibatis.sqlmap.engine.transaction.TransactionException: TransactionManager could not start a new transaction.  A transaction is already started.
Caused by: com.ibatis.sqlmap.engine.transaction.TransactionException: TransactionManager could not start a new transaction.  A transaction is already started.
at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.startTransaction(SqlMapExecutorDelegate.java:728)
at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.startTransaction(SqlMapSessionImpl.java:125)
at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.startTransaction(SqlMapClientImpl.java:102)
at com.vodone.cpms.dao.impl.MessageDaoImpl.addMessages(MessageDaoImpl.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.ibatis.dao.engine.impl.DaoProxy.invoke(DaoProxy.java:72)
at $Proxy1.addMessages(Unknown Source)

原因是ibatis在执行批量更新或保存的时候会新起一个事务,我们在批量更新的上面已经开始了事务,当我们开始批量操作时就会造成嵌套的事务而报错,把批量更新前的事务代码去掉就ok了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值