浅谈mybatis的executor

本文详细介绍了Mybatis Executor组件的创建、MappedStatement的配置和使用,包括基本的插入更新操作及debug过程。重点展示了Executor在数据库操作中的核心作用和批量处理机制的简要概述。
摘要由CSDN通过智能技术生成

executor 作为mybatis 的执行组件,是Mybatis 的组件之一。
将执行数据库的操作的。
基本的executor的测试:
一。基本处理
我们做个测试:

//创建executor 对象
Executor executor = createExecutor(new JdbcTransaction(ds, null, false));

//mappedStatement 对象
    try {
      Author author = new Author(-1, "someone", "******", "someone@apache.org", null, Section.NEWS);
      MappedStatement insertStatement = ExecutorTestHelper.prepareInsertAuthorMappedStatementWithBeforeAutoKey(config);
      MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatement(config);
 //执行插入更新操作
      int rows = executor.update(insertStatement, author);
      assertTrue(rows > 0 || rows == BatchExecutor.BATCH_UPDATE_RETURN_VALUE);
      if (rows == BatchExecutor.BATCH_UPDATE_RETURN_VALUE) {
        executor.flushStatements();
      }
      assertEquals(123456, author.getId());
      if (author.getId() != BatchExecutor.BATCH_UPDATE_RETURN_VALUE) {
        List<Author> authors = executor.query(selectStatement, author.getId(), RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
        executor.rollback(true);
        assertEquals(1, authors.size());
        assertEquals(author.toString(), authors.get(0).toString());
        assertTrue(author.getId() >= 10000);
      }
    } finally {
      executor.rollback(true);
      executor.close(false);
    }

如上主要进行创建executeor 方法,mappedStatement 对象的创建,执行插入更新操作执行。

debug:
首先创建:

 protected Executor createExecutor(Transaction transaction) {
    return new SimpleExecutor(config, transaction);
  }

注入参数:

 static MappedStatement prepareInsertAuthorMappedStatementWithBeforeAutoKey(final Configuration config) {
    final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
    final ResultMap rm = new ResultMap.Builder(config, "keyResultMap", Integer.class, new ArrayList<>())
        .build();

    MappedStatement kms = new MappedStatement.Builder(config, "insertAuthor!selectKey", new StaticSqlSource(config,"SELECT 123456 as id FROM SYSIBM.SYSDUMMY1"), SqlCommandType.SELECT)
        .keyProperty("id")
        .resultMaps(new ArrayList<ResultMap>() {
          {
            add(rm);
          }
        })
        .build();
    config.addMappedStatement(kms);
    return new MappedStatement.Builder(config, "insertAuthor", new DynamicSqlSource(config, new TextSqlNode("INSERT INTO author (id,username,password,email,bio,favourite_section) values(#{id},#{username},#{password},#{email},#{bio:VARCHAR},#{favouriteSection})")), SqlCommandType.INSERT)
        .parameterMap(
            new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>() {
              {
                add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(Integer.class)).build());
                add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
                add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
                add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
                add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
                add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build());
              }
            }).build())
        .cache(authorCache)
        .keyGenerator(new SelectKeyGenerator(kms, true))
        .keyProperty("id")
        .build();
  }


}

这里设置 向mybatis注入sql语句完成插入预编译,然后进行赋值操作,
完成一个update 操作:
源码如下:

@Override
  public int update(MappedStatement ms, Object parameter) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    clearLocalCache();
    return doUpdate(ms, parameter);
  }

执行update 方法如下:

@Override
    public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
      final Configuration configuration = ms.getConfiguration();
      final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
      final BoundSql boundSql = handler.getBoundSql();
      final String sql = boundSql.getSql();
      final Statement stmt;
      if (sql.equals(currentSql) && ms.equals(currentStatement)) {
        int last = statementList.size() - 1;
        stmt = statementList.get(last);
        applyTransactionTimeout(stmt);
        handler.parameterize(stmt);// fix Issues 322
        BatchResult batchResult = batchResultList.get(last);
        batchResult.addParameterObject(parameterObject);
      } else {
        Connection connection = getConnection(ms.getStatementLog());
        stmt = handler.prepare(connection, transaction.getTimeout());
        handler.parameterize(stmt);    // fix Issues 322
        currentSql = sql;
        currentStatement = ms;
        statementList.add(stmt);
        batchResultList.add(new BatchResult(ms, sql, parameterObject));
      }
      handler.batch(stmt);
      return BATCH_UPDATE_RETURN_VALUE;
    }

底层调用JDBC处理。
二。批量处理:这里暂略

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值