---
title: "Cannot change the ExecutorType when there is an existing transaction"
author: "penggle"
date: "2013-10-23T19:45:42Z"
tags: []
categories: ["编程语言"]
slug: "cannot-change-the-executortype-when-there-is-an-existing-transaction"
draft: false
lastmod: "2014-10-30T19:44:53Z"
id: 1963336
url: "https://penggle.iteye.com/blog/1963336"
---

```java

但凡使用mybatis，同时与spring集成使用时，接下来要说的这个问题是躲不了的。众所周知，mybatis的SqlSessionFactory在获取一个SqlSession时使用默认Executor或必须要指定一个Executor，这样一来，在同一个SqlSession的生命周期中，要想切换Executor是不可能的，比如在一个复杂业务中：
sqlSession.insert("insertMainOrder", mainOrder); // -----(1)

for(OrderInfo childOrder : childOrderList){      // -----(2)
    sqlSession.insert("insertChildOrder", childOrder);
}

如果sqlSession使用ExecutorType.SIMPLE open出来的话,(2)处如果是用Jdbc batch操作将是不可能的,当然(2)处如果你再新open一个ExecutorType.BATCH的新的SqlSession的话：A、如果整个业务在无事务环境下运行的话，则不会报错，但是底层会使用多个不同的Connection，浪费资源，最重要的是无法保持在同一个事务中。B、如果整个业务在一个事务中运行的话(如propagation=Propagation.REQUIRED)，则会在mybatis-spring框架中报错：TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction")，究其原因是因为在mybatis-spring框架中在有事务情况下SqlSession是通过sessionFactory与当前线程绑定的，新open出来的SqlSession会与上一个使用的SqlSession的ExecutorType进行比较，如果ExecutorType改变了，则直接报错。

针对这个问题，本人基于mybatis、mybatis-spring框架基础上，通过继承扩展，解决了这个问题。

扩展后，也经过了一些测试，非常成功，得到了预期的结果：
1、一个完整复杂业务中从头到尾使用同一个SqlSession，使用jdbc batch操作(ExecutorType=BATCH)和非batch的普通操作(ExecutorType=SIMPLE)混搭的模式
2、修改过后测试了mybatis事务、spring事务等均符合预期

项目地址：https://github.com/penggle/mybatis-ex
该项目已经发布到maven中央库上：
maven:
      <groupId>com.github.penggle</groupId>
      <artifactId>mybatis-ex</artifactId>
      <version>1.0.0</version>
      <name>mybatis-ex</name>
gradle:
      compile("com.github.penggle:mybatis-ex:1.0.0")

```