Mybatis源碼[01.SqlSessionFactoryBuilder]

可以說每個MyBatis都是以一個SqlSessionFactory實例爲中心的。SqlSessionFactory實例可以通過SqlSessionFactoryBuilder來構建。一是可以通過XML配置文件的方式來構建SqlSessionFactory,二是可以通過Java API的方式來構建。但不管通過什麼方式都有一個Configuration貫穿始終,各種配置正是通過Configuration實例來完成實現。

public class SqlSessionFactoryBuilder {

  // (1) 從配置文件獲取SqlSessionFactory
  public SqlSessionFactory build(Reader reader) {
    return build(reader, null, null);
  }

  // (2) 從配置文件獲取SqlSessionFactory,並設定依賴哪種環境參數(開發環境/生產環境)
  public SqlSessionFactory build(Reader reader, String environment) {
    return build(reader, environment, null);
  }

  // (3) 從配置文件獲取SqlSessionFactory,並設定依賴哪些配置參數(屬性配置文件,那些屬性可以用${propName}語法形式多次用在配置文件中)
  public SqlSessionFactory build(Reader reader, Properties properties) {
    return build(reader, null, properties);
  }

  // 通用構建函數-:(1)、(2)、(3)構建函數內部實現均調用的此函數
  public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      //委託XMLConfigBuilder來解析xml文件,並返回一個Configuration對象,SqlSessionFactory的生成依賴於此Configuration對象
      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.
      }
    }
  }

  // (4) 從數據流中獲取SqlSessionFactory
  public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
  }

  // (5) 從數據流中獲取SqlSessionFactory,並設定依賴哪種環境參數(開發環境/生產環境)
  public SqlSessionFactory build(InputStream inputStream, String environment) {
    return build(inputStream, environment, null);
  }

  // (6) 從數據流中獲取SqlSessionFactory,並設定依賴哪些配置參數(屬性配置文件,那些屬性可以用${propName}語法形式多次用在配置文件中)
  public SqlSessionFactory build(InputStream inputStream, Properties properties) {
    return build(inputStream, null, properties);
  }

  // 通用構建函數二:(4)、(5)、(6)構建函數內部實現均調用此函數
  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.
      }
    }
  }

  // 通用構建函數一和通用構建函數二最終調用此函數,將XMLConfigBuilder 產生的Configuration作爲參數,並返回DefaultSqlSessionFactory對象
  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章