- SimpleExecutor – SIMPLE 就是普通的执行器。
- ReuseExecutor -执行器会重用预处理语句(prepared statements)
- BatchExecutor –它是批量执行器
这些就是Mybatis的三种执行器。你可以通过配置文件的settings里面的元素defaultExecutorType,配置它,默认是采用SimpleExecutor如果你在Spring运用它,那么你可以这么配置它:
<bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!--更新采用批量的executor --> <constructor-arg index="1" value="BATCH"/> </bean>
或者在Spring Boot的属性文件中配置:
mybatis.executor-type=BATCH
如果你在事务中有这么一段代码:
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。
这时,只需要修改Executor为其它两种即可:
<bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!--更新采用批量的executor --> <constructor-arg index="1" value="SIMPLE"/> </bean>
或者在Spring Boot的属性文件中配置:
mybatis.executor-type=SIMPLE