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