`
234390216
  • 浏览: 10194143 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
博客专栏
A5ee55b9-a463-3d09-9c78-0c0cf33198cd
Oracle基础
浏览量:460821
Ad26f909-6440-35a9-b4e9-9aea825bd38e
springMVC介绍
浏览量:1771877
Ce363057-ae4d-3ee1-bb46-e7b51a722a4b
Mybatis简介
浏览量:1395481
Bdeb91ad-cf8a-3fe9-942a-3710073b4000
Spring整合JMS
浏览量:393917
5cbbde67-7cd5-313c-95c2-4185389601e7
Ehcache简介
浏览量:678253
Cc1c0708-ccc2-3d20-ba47-d40e04440682
Cas简介
浏览量:529320
51592fc3-854c-34f4-9eff-cb82d993ab3a
Spring Securi...
浏览量:1178774
23e1c30e-ef8c-3702-aa3c-e83277ffca91
Spring基础知识
浏览量:462010
4af1c81c-eb9d-365f-b759-07685a32156e
Spring Aop介绍
浏览量:150169
2f926891-9e7a-3ce2-a074-3acb2aaf2584
JAXB简介
浏览量:66890
社区版块
存档分类
最新评论

Mybatis的Executor介绍(二)——批处理,批量更新

阅读更多

6       MybatisExecutor介绍(二)——批处理

       在程序中,有时候我们需要批量的去操作一些数据,批量的新增、修改、删除,如果是通过for循环一条记录一条记录的去更新无疑效率会比较慢。更佳的做法无疑是采用JDBC对批处理的支持。Mybatis基于JDBC对批处理的支持,也提供了进行数据的批量操作的APIBatchExecutor。下面是一段JDBC进行批量操作的示例代码。

   @Test

   public void testJDBCBatch() throws SQLException {

      String sql = "insert into t_user(name, mobile, email) values(?,?,?)";

      try (Connection conn = dataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql);) {

        List<User> users = this.getUsers();

        for (User user : users) {

           pstmt.setString(1, user.getName());

           pstmt.setString(2, user.getMobile());

           pstmt.setString(3, user.getEmail());

           pstmt.addBatch();

        }

        pstmt.executeBatch();

        conn.commit();

      }

   }

 

       在每一次调用的时候是调用Statement.addBatch()方法,最终所有的参数都传递完了,没有更多的参数时调用Statement.executeBatch()方法进行批量操作。在上一篇博文中我们查看了BatchExecutor的源码,它的核心代码doUpdate()方法,每次被调用的时候都是以handler.batch()结束,而handler.batch()对应的底层代码是调用对应的StatementaddBatch()方法。那它是在什么时候执行executeBatch()呢?

  @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)) {

      intlast = statementList.size() - 1;

      stmt = statementList.get(last);

     handler.parameterize(stmt);//fix Issues 322

      BatchResult batchResult = batchResultList.get(last);

      batchResult.addParameterObject(parameterObject);

    } else {

      Connection connection = getConnection(ms.getStatementLog());

      stmt = handler.prepare(connection);

      handler.parameterize(stmt);    //fix Issues 322

      currentSql = sql;

      currentStatement = ms;

      statementList.add(stmt);

      batchResultList.add(new BatchResult(ms, sql, parameterObject));

    }

  // handler.parameterize(stmt);

    handler.batch(stmt);

    return BATCH_UPDATE_RETURN_VALUE;

  }

 

       它的executeBatch()是在doFlushStatements()方法调用中调用的,它会在当前Executor进行commit时调用,也会在当前Executor第一次执行doQuery()时调用,在这个时候都会调用ExecutorflushStatements()方法,而BaseExecutor在执行flushStatements()时最终会调用其doFlushStatements()方法。当然,我们也可以手动的调用SqlSessionflushStatements()方法,其底层实现也会调用对应的BaseExecutorflushStatements()方法。

  @Override

  public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {

    try {

      List<BatchResult> results = new ArrayList<BatchResult>();

      if (isRollback) {

        return Collections.emptyList();

      }

      for (int i = 0, n = statementList.size(); i < n; i++) {

        Statement stmt = statementList.get(i);

        BatchResult batchResult = batchResultList.get(i);

        try {

          batchResult.setUpdateCounts(stmt.executeBatch());

          MappedStatement ms = batchResult.getMappedStatement();

          List<Object> parameterObjects = batchResult.getParameterObjects();

          KeyGenerator keyGenerator = ms.getKeyGenerator();

          if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {

            Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;

            jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);

          } else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) { //issue #141

            for (Object parameter : parameterObjects) {

              keyGenerator.processAfter(this, ms, stmt, parameter);

            }

          }

        } catch (BatchUpdateException e) {

          StringBuilder message = new StringBuilder();

          message.append(batchResult.getMappedStatement().getId())

              .append(" (batch index #")

              .append(i + 1)

              .append(")")

              .append(" failed.");

          if (i > 0) {

            message.append(" ")

                .append(i)

                .append(" prior sub executor(s) completed successfully, but will be rolled back.");

          }

          throw new BatchExecutorException(message.toString(), e, results, batchResult);

        }

        results.add(batchResult);

      }

      return results;

    } finally {

      for (Statement stmt : statementList) {

        closeStatement(stmt);

      }

      currentSql = null;

      statementList.clear();

      batchResultList.clear();

    }

  }

 

       下面是一个使用MybatisBatchExecutor进行批量操作的示例。在示例中我们创建了一个使用BatchExecutorSqlSession,也可以是SqlSessionTemplate,其实现了SqlSession接口,底层通过一个SqlSession代理进行相应的操作。然后在循环中一次调用对应Mapper的新增操作,相当于调用BatchExecutordoUpdate(),最后调用SqlSessioncommit()方法提交事务,在SqlSessioncommit()中会调用Executorcommit(),从而导致了executeBatch()的发生。

   @Test

   public void testExecutor() {

      SqlSession session = this.sessionFactory.openSession(ExecutorType.BATCH);

      UserMapper mapper = session.getMapper(UserMapper.class);

      User user = null;

      for (inti = 0; i < 10; i++) {

        user = new User();

        user.setName("Name_" + i);

        user.setEmail("email");

        mapper.insert(user);

      }

      // 批量插入User

      session.commit();// 提交事务时批量操作才会写入数据库

      session.close();

   }

 

参考文档

       Mybatis源码

 

(注:本文是基于Mybatis3.3.1所写,写于20161224日星期六)

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics