mybatis 批量处理时自动提交的问题

Spring 中默认的事务工厂 SpringTransactionFactory 时每次执行 flushStatements() 方法后事务会立即提交,代码中的 SqlSession.commit(), SqlSession.rollback() or SqlSession.close() 不能影响 Spring 管理的SqlSession,不管 autocommit 怎么设置,在 Spring 事务外面执行 SqlSession 的任何数据操作或者调用 mapper 中的方法都会立即提交[参见资料2]。

MyBatis SqlSession provides you with specific methods to handle transactions programmatically. But when using MyBatis-Spring your beans will be injected with a Spring managed SqlSession or a Spring managed mapper. That means that Spring will always handle your transactions.

You cannot call SqlSession.commit(), SqlSession.rollback() or SqlSession.close() over a Spring managed SqlSession. If you try to do so, a UnsupportedOperationException exception will be thrown. Note these methods are not exposed in injected mapper classes.

Regardless of your JDBC connection's autocommit setting, any execution of a SqlSession data method or any call to a mapper method outside a Spring transaction will be automatically committed.

解决办法:使用 JDBC 事务工厂

<bean id="transactionFactory" class="org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory" />
<bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="configLocation" value="config/mybatis-config-spring.xml" />
    <property name="dataSource" ref="dataSource" />
    <property name="transactionFactory" ref="transactionFactory" />
</bean>


参考资料
1. SpringManagedTransactionFactory always ignore autoCommit. https://github.com/mybatis/spring/issues/39
2. mybatis-spring Transactions. http://www.mybatis.org/spring/transactions.html
3. mybatis Java API(中文版). http://www.mybatis.org/mybatis-3/zh/java-api.html
4. mybatis Java API. http://www.mybatis.org/mybatis-3/java-api.html
5. mybatis Configuration. http://www.mybatis.org/mybatis-3/configuration.html
6. mybatis全局配置文件mybatis-config.xml. https://www.jianshu.com/p/2756e81d02ff
7. 谈jdbcTemplate与mybatis. https://www.cnblogs.com/ChenD/p/7080934.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值