mybatis --执行器

执行器的种类

  • 简单执行器 (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));
    }
  1. 构建SimpleExecutor对象
  2. 构建MappedStatement对象
  3. 执行两次相同的查询方法(参数也相同)
    看一下执行结果 :
    在这里插入图片描述
    可以看到, 即使是相同的执行语句 , 也需要进行两次预编译

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);, 数据库才会生效==

使用时可以根据不同的业务场景, 选择不同的执行器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值