MyBatis框架的使用及源碼分析(五) DefaultSqlSessionFactory和DefaultSqlSession


我們回顧<MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置與使用> 一文的示例

private static SqlSessionFactory getSessionFactory() {
    SqlSessionFactory sessionFactory = null;
    String resource = "mybatisConfig.xml";
    try {
        sessionFactory = new SqlSessionFactoryBuilder().build(Resources
                .getResourceAsReader(resource));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sessionFactory;
}

@Test
public void findUserById() {
    SqlSessionFactory sqlSessionFactory = getSessionFactory();
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.selectByPrimaryKey(1l);
    System.out.println(user.getId() + " /  " + user.getName());
}

 

SqlSessionFactoryBuilder 創建出SqlSessionFactory,然后從SqlSessionFactory中得到SqlSession,最后通過SqlSession得到Mapper接口對象進行數據庫操作。

我們跟蹤SqlSessionFactoryBuilder的源代碼:

package org.apache.ibatis.session;

public class SqlSessionFactoryBuilder {

public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        reader.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }
    
  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

}

我們可以看到這個類用很多的構造方法,但主要分為三大類:
1、通過讀取字符流(Reader)的方式構件SqlSessionFactory。
2、通過字節流(InputStream)的方式構件SqlSessionFacotry。
3、通過Configuration對象構建SqlSessionFactory。
第1、2種方式是通過配置文件方式,第3種是通過Java代碼方式。
build方法返回SqlSessionFactory接口的實現對象DefaultSqlSessionFactory。

我們繼續跟蹤DefaultSqlSessionFactory的openSession()方法:

package org.apache.ibatis.session.defaults;

/**
 * @author Clinton Begin
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

  private final Configuration configuration;

  public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
  }

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

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

  public SqlSession openSession(ExecutorType execType) {
    return openSessionFromDataSource(execType, null, false);
  }

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

  public SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level) {
    return openSessionFromDataSource(execType, level, false);
  }

  public SqlSession openSession(ExecutorType execType, boolean autoCommit) {
    return openSessionFromDataSource(execType, null, autoCommit);
  }

  public SqlSession openSession(Connection connection) {
    return openSessionFromConnection(configuration.getDefaultExecutorType(), connection);
  }

  public SqlSession openSession(ExecutorType execType, Connection connection) {
    return openSessionFromConnection(execType, connection);
  }

  public Configuration getConfiguration() {
    return configuration;
  }

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

  private SqlSession openSessionFromConnection(ExecutorType execType, Connection connection) {
    try {
      boolean autoCommit;
      try {
        autoCommit = connection.getAutoCommit();
      } catch (SQLException e) {
        // Failover to true, as most poor drivers
        // or databases won't support transactions
        autoCommit = true;
      }      
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      final Transaction tx = transactionFactory.newTransaction(connection);
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
    if (environment == null || environment.getTransactionFactory() == null) {
      return new ManagedTransactionFactory();
    }
    return environment.getTransactionFactory();
  }

  private void closeTransaction(Transaction tx) {
    if (tx != null) {
      try {
        tx.close();
      } catch (SQLException ignore) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

}

這么多的openSession重載方法,都是通過傳入不同的參數構造SqlSession實例,有通過設置事務是否自動提交"autoCommit",有設置執行器類型"ExecutorType"來構造的,還有事務的隔離級別等等。
最后一個方法就告訴我們可以通過SqlSessionFactory來獲取Configuration對象。

mybatis創建sqlsession經過了以下幾個主要步驟: 

1.       從核心配置文件mybatis-config.xml中獲取Environment(這里面是數據源);
2.       從Environment中取得DataSource;
3.       從Environment中取得TransactionFactory;
4.       從DataSource里獲取數據庫連接對象Connection;
5.       在取得的數據庫連接上創建事務對象Transaction;
6.       創建Executor對象(該對象非常重要,事實上sqlsession的所有操作都是通過它完成的);
7.       創建sqlsession對象。

 

從源碼中可以知道DefaultSqlSession是SqlSession的實例。

new DefaultSqlSession(configuration, executor, autoCommit);

 

那么通過此文,我們就清楚的知道了SqlSessionFactory和SqlSession具體的創建過程,知道了他們的實現類是DefaultSqlSessionFactory和DefaultSqlSession。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM