Mybatis架构设计及源码分析-SqlSessionFactory

Mybatis作为一个ORM框架目前在企业级开发中使用之非常多,说到ORM框架Mybatis其实并不算一个完整的ORM框架这个在Mybatis文档中也有说明,确实Mybtais只是实现了访问数据库的过程我们还是需要自己去写sql语句,当然正是这种妙处使得Mybatis的灵活性非常大。SqlSessionFactory是mybatis中的重要组件,下面我们还是回到编程式使用mybatis的例子上面来,上一篇文章已经分析了Configuration对象的初始化过程了,初始化后将会根据Configuration对象生成SqlSessionFactory组件,下面将具体分析下过程。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="false"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.github.wenbo2018.dao.UserDao" alias="User"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/> <!--事务管理类型-->
            <dataSource type="POOLED">
                <property name="username" value="test"/>
                <property name="password" value="123456"/>
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.1.150/ssh_study"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="userMapper.xml"/>
    </mappers>

</configuration>
        String resource = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
            List<Product> productList = productMapper.selectProductList();
            for (Product product : productList) {
                System.out.printf(product.toString());
            }
        } finally {
            sqlSession.close();
        }
public SqlSessionFactory build(Configuration config) {
  return new DefaultSqlSessionFactory(config);
}

这面代码生成了SqlSessionFactory,可以看出默认的实现是DefaultSqlSessionFactory,SqlSessionFactory接口比较简单主要是一些打开并获取SqlSession的方法。默认使用下面方法:

 SqlSession sqlSession = sqlSessionFactory.openSession();

最终调用的方法是:

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);
      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();
    }
  }

代码中首先获取到Environment信息,接口从环境Environment获取到事务工厂TransactionFactory,默认Environment没有事务工厂的会使用ManagedTransactionFactory,一般情况下直接使用mybatis会使用JDBC事务(暂时不考虑与Spring集成)。

final Executor executor = configuration.newExecutor(tx, execType);

这句代码是生成一个Executor,Executor是mybatis的重要组件之一,是执行sql的重要部分,后续详细分析,我们看看他是如何生成。

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;
  }


executorType从前面可以看到默认使用的是ExecutorType.SIMPLE模式。故这里执行的是executor = new SimpleExecutor(this, transaction);这句代码,我们也可以通过以下方法来执行生成具体的Executor:

SqlSession openSession(boolean autoCommit);
  SqlSession openSession(Connection connection);
  SqlSession openSession(TransactionIsolationLevel level);

  SqlSession openSession(ExecutorType execType);
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);

各种executor的区别这里暂时不分析,后续详细分析。如果cacheEnabled开关被打开的话会使用CachingExecutor,默认情况下cacheEnabled=true,故这里使用的是CachingExecutor。

executor = (Executor) interceptorChain.pluginAll(executor);

这句代码是将executor注入的拦截器链中,之前分析过我们可以自己编写插件这样执行sql语句时会执行拦截调用。暂时不具体分析调用过程,初步看代代码这里使用了一个装饰器模式。

final Executor executor = configuration.newExecutor(tx, execType);

这句代码后得到的是CachingExecutor,带有缓存功能。接着构造sqlsession,使用的是DefaultSqlSession

return new DefaultSqlSession(configuration, executor, autoCommit);

猜你喜欢

转载自my.oschina.net/wenbo123/blog/1819279