BATCH模式
在全局配置文件的setting中,有一个属性可以设置ExecutorType
的类型,默认为SIMPLE
,但是通常我们不会在全局配置文件中进行设置。
在使用中,通常在获取SqlSession
的时候加以参数进行配置,SqlSession openSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
,以往我们都是使用不带参数的进行打开Session,这里使用带参数的进行获取,可以获取到支持批量操作的SqlSession。
BATCH模式执行效果
如上图所示,BATCH模式,只发出一条SQL语句,预编译一次,但设置参数N次,执行一次。
SIMPLE模式执行效果
如上图所示,SIMPLE模式,每一条语句都会发出一条SQL,进行一次预编译,设置一次参数,执行一次。
耗时对比
同时插入1W条记录,BATCH耗时4266
,SIMPLE耗时1109
,差了基本上4倍。可见效率上差别很大。
Spring整合
配置
在Spring的配置文件中,加入一个进行批量执行的SqlSession的bean。
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- configLocation:指定全局配置文件的位置 -->
<property name="configLocation"
value="classpath:mybatis-config.xml"></property>
<!-- mapperLocations:指定mapper文件的位置 ,不配置Mapper接口和Mapper配置的包名必须相同 -->
<property name="mapperLocations"
value="classpath:mybatis/mapper/*.xml"></property>
</bean>
<!-- 配置一个可以进行批量执行的SqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
第一个bean是我们的SqlSessionFactory,我们为其指定ID。
第二个bean是支持批量执行的SqlSession
,他有几个构造器,其中可以指定SqlSessionFactory和ExecutorType,这样我们就能得到一个BATCH模式的SqlSession的bean。
使用
已经配置了一个BATCH模式的sqlSession,在使用的地方,我们添加一个SqlSession对象,让Spring为其自动注入即可,相当于SqlSession openSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
。如下面的一个Service。
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private SqlSession sqlSession;
public List<Employee> getEmps() {
//这个sqlSession就是BATCH模式的
//EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
return employeeMapper.getEmps();
}
}
这里的sqlSession就会被Spring自动注入,由于org.mybatis.spring.SqlSessionTemplate
实现了SqlSession接口
,它其实就是一个SqlSession,故会按照类型
进行自动注入。