zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    学习制作操作系统 0
    阅读《C陷阱与缺陷》的知识增量
    CSS 优先级和特指度
    openCV2马拉松第19圈——Harris角点检測(自己实现)
    Cacti监控mysql数据库server实现过程
    ledisdb:支持类redis接口的嵌入式nosql
    03005_SQL查询语句
    通过smtp直接发送邮件
    XML 解析默认去掉命名空间和注释
    C# /VB.NET 创建PDF项目符号列表和多级编号列表
  • 原文地址:https://www.cnblogs.com/zsg88/p/7551536.html
Copyright © 2011-2022 走看看