执行器的种类
- 简单执行器 (SimpleExecutor)
- 可重用执行器 (ReuseExecutor)
- 批处理执行器 (BatchExecutor)
执行器的使用
@BeforeEach
public void init() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
configuration = factory.getConfiguration();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis","root","123456");
jdbcTransaction = new JdbcTransaction(connection);
}
SimpleExecutor
@Test
public void simpleExecutorTest() throws Exception{
SimpleExecutor executor = new SimpleExecutor(configuration,jdbcTransaction);
MappedStatement mappedStatement = configuration.getMappedStatement("com.hctrl.mybatis.mapper.UserMapper.selectById");
executor.doQuery(mappedStatement,1 , RowBounds.DEFAULT,
SimpleExecutor.NO_RESULT_HANDLER, mappedStatement.getBoundSql(10));
executor.doQuery(mappedStatement,1 , RowBounds.DEFAULT,
SimpleExecutor.NO_RESULT_HANDLER, mappedStatement.getBoundSql(10));
}
- 构建SimpleExecutor对象
- 构建MappedStatement对象
- 执行两次相同的查询方法(参数也相同)
看一下执行结果 :
可以看到, 即使是相同的执行语句 , 也需要进行两次预编译
ReuseExecutor
@Test
public void reuseExecutorTest() throws Exception{
ReuseExecutor executor = new ReuseExecutor(configuration,jdbcTransaction);
MappedStatement mappedStatement = configuration.getMappedStatement("com.hctrl.mybatis.mapper.UserMapper.selectById");
executor.doQuery(mappedStatement,1 , RowBounds.DEFAULT,
SimpleExecutor.NO_RESULT_HANDLER, mappedStatement.getBoundSql(10));
executor.doQuery(mappedStatement,1 , RowBounds.DEFAULT,
SimpleExecutor.NO_RESULT_HANDLER, mappedStatement.getBoundSql(10));
}
执行结果 :
== 两次相同的查询 只进行了一次预编译==
BatchExecutor
批处理执行只要的使用场景就是进行批量插入, 批量更新等操作
/**
* 批处理执行器
* 只针对修改操作
* 批处理操作必须手动刷新, 数据库才会生效
* @throws Exception
*/
@Test
public void batchExecutorTest() throws Exception{
BatchExecutor executor = new BatchExecutor(configuration,jdbcTransaction);
MappedStatement mappedStatement = configuration.getMappedStatement("com.hctrl.mybatis.mapper.UserMapper.updateNameById");
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("id",1);
paramMap.put("name","hanchao");
executor.doUpdate(mappedStatement, paramMap);
executor.doFlushStatements(false);
}
== 批处理操作必须手动刷新executor.doFlushStatements(false);, 数据库才会生效==
使用时可以根据不同的业务场景, 选择不同的执行器