Springboot+mybatis事务回滚时报错处理。Cannot change the ExecutorType when there is an existing transaction

问题详情

org.springframework.dao.TransientDataAccessResourceException: Cannot change the ExecutorType when there is an existing transaction

	at org.mybatis.spring.SqlSessionUtils.sessionHolder(SqlSessionUtils.java:157)
	at org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:91)
	at com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper.sqlSessionBatch(SqlHelper.java:55)
	at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.sqlSessionBatch(ServiceImpl.java:75)
	at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.updateBatchById(ServiceImpl.java:247)
	at com.baomidou.mybatisplus.extension.service.IService.updateBatchById(IService.java:148)
	at com.streamax.maintenance.model.dao.BaseDao.delete(BaseDao.java:133)
	at com.streamax.maintenance.model.dao.BaseDao.deleteByExactParams(BaseDao.java:187)

详情分析:

https://www.cnblogs.com/nizuimeiabc1/p/9559461.html

总结:

mybatis的执行器有三种类型:

  • ExecutorType.SIMPLE

这个类型不做特殊的事情,它只为每个语句创建一个PreparedStatement。

  • ExecutorType.REUSE

这种类型将重复使用PreparedStatements。

  • ExecutorType.BATCH

这个类型批量更新,性能更优,但batch模式也有自己的问题,比如在Insert操作时,在事务没有提交之前,是没有办法获取到自增的id,这在某型情形下是不符合业务要求的,而且假如有一条sql语句报错,则整个事务回滚,虽然这条sql语句不是太重要。注意:在同一事务中batch模式和simple模式之间无法转换。

 

最后采用的解决方法

  1. 批量更新的时候,先把所有更新的对象查出来,然后循环更新。
  2. ExecutorType.BATCH,全部改成batch模式。但是没有办法获取到自增的id,spring事务一起使用,将无法回滚,必须注意,最好单独使用。需要用到一个类:MyBatisBatchItemWriter,它是批量执行更新操作。
posted @ 2019-06-13 13:53  dyigstraw  阅读(654)  评论(0编辑  收藏  举报
foot