解决由于设置Mybatis的BatchExecutor批量执行器而导致无法获取自增Id的问题

在Mybatis中有三种Executor:

  • SimpleExecutor — SIMPLE 就是普通的执行器。
  • ReuseExecutor -执行器会重用预处理语句(prepared statements)
  • BatchExecutor —它是批量执行器

这些就是Mybatis的三种执行器。你可以通过配置文件的settings里面的元素defaultExecutorType,配置它,默认是采用SimpleExecutor如果你在Spring运用它,那么你可以这么配置它:

1
2
3
4
5
<bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate">     
<constructor-arg index="0" ref="sqlSessionFactory" />
<!--更新采用批量的executor -->
<constructor-arg index="1" value="BATCH"/>
</bean>

或者在Spring Boot的属性文件中配置:

1
mybatis.executor-type=BATCH

如果你在事务中有这么一段代码:

1
2
3
4
5
6
7
8
9
Media media = new Media();
media.setTitle("默认用户头像");
media.setMediaType(0);
media.setUrl(defaultAvatarUrl);
mediaMapper.insert(media);
logger.info("mediaId : " + media.getId());
User user = new User();
user.setMedia(media);
userMapper.insert(user);

那么就会导致Media无法获取插入数据库后的id。

这是由于设置了executorType=BATCH而导致执行更新Sql时Mybatis没有提交语句到数据库。

这时有两种解决方法:

方法1:

只需要修改Executor为其它两种SIMPLE or REUSE即可:

1
2
3
4
<bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate">     
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="SIMPLE"/>
</bean>

或者在Spring Boot的属性文件中配置:

1
mybatis.executor-type=SIMPLE

方法2:

在insert方法之后执行:

1
2
// 刷新批量更新语句缓存,将Sql语句发送到数据库执行
sqlSession.flushStatements();

以上,如有问题欢迎提出!

如果对您有所帮助,欢迎投食!
0%