Mybatisソース[01.Sql Session FactoryBuider]


各MyBatisはSql Session Factoryの実例を中心としていると言える。Sql Session Factory例はSql Session FactoryBuiderによって構築できる。一つは、Sql Session FactoryをXMLプロファイルで構築することができ、もう一つはJava APIで構築することができる。しかし、どのような方法でも終始一貫してConfigrationがあり、様々な構成がConfigrationのインスタンスによって実現される。
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);
  }

}