Java教程

Mybatis源码学习(二)简单Demo的运行原理

本文主要是介绍Mybatis源码学习(二)简单Demo的运行原理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

0 回顾

上一节,我们写了一个简单Demo,并看到了它的运行结果,这一节,我们分析一下Mybatis执行sql的原理。

 

public class MybatisMain {
  public static void main(String[] args) throws IOException
  {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
    System.out.println(blog.getContext());
  }
}

1 解析配置文件

InputStream inputStream = Resources.getResourceAsStream(resource);

这一行代码,解析mybatis-config.xml文件,得到一个输入流。我们把xml文件也贴出来

<configuration>
    <properties resource="jdbc.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/BlogMapper.xml"/>
    </mappers>
</configuration>

这个xml中有3个配置:jdbc.properties,environments,mappers

2 SqlSessionFactory

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

这里,得到一个SqlSessionFactory对象,执行完这行代码,实现了对上述xml文件的解析,把配置都保存在该对象的成员变量configuration中。

 

 

这些配置信息包括:数据库连接信息、所有Mapper

3 SqlSession

SqlSession sqlSession = sqlSessionFactory.openSession();

该行代码返回SqlSession对象,该对象中包含一个executor变量,默认为CachingExecutor对象(一级缓存)。这个executor对象是实际查询时的执行器。

  public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

这里调用了openSessionFromDataSource方法

  private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx, execType);//public enum ExecutorType {SIMPLE, REUSE, BATCH},默认为SIMPLE
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

 创建Executor,默认创建的是SimpleExecutor,如果开启了一级缓存,则使用CachingExecutor进行了封装。

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

最终返回一个包含CachingExecutor对象的SqlSession。

 

 

4 执行查询

Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);

 执行selectOne方法

  public <T> T selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    List<T> list = this.selectList(statement, parameter);
    if (list.size() == 1) {
      return list.get(0);
    } else if (list.size() > 1) {
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
      return null;
    }
  }

执行selectList方法

  private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

调用CachingExecutor的query方法,判断缓存中是否有记录,如果有,取缓存中的记录,如果没有,则调用SimpleExecutor中的query查询数据库

  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

然后,执行SimpleExecutor的doQuery方法

  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

这个方法就是我们使用JDBC查询数据库的代码。

我们再回到刚开始的这行代码

Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);

从上面分析来看,我们执行这行代码之后,最终返回给我们的是一个Blog对象,包含了数据库记录。

这就是我们执行mybatis的过程。

这篇关于Mybatis源码学习(二)简单Demo的运行原理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!