首先我们看看SqlSessionFactory是怎么获取的?
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
从上面我们很清楚的知道SqlSessionFactory是借助于SqlSessionFactoryBuilder的build方法构建出来的,那么build方法为我们做了什么呢?
SqlSessionFactoryBuilder 有以下 build() 方法,每一种都允许你从不同的资源中创建一个 SqlSessionFactory 实例。
SqlSessionFactory build(Reader reader)
SqlSessionFactory build(Reader reader, String environment)
SqlSessionFactory build(Reader reader, Properties properties)
SqlSessionFactory build(Reader reader, String env, Properties props)
SqlSessionFactory build(InputStream inputStream)
SqlSessionFactory build(InputStream inputStream, String environment)
SqlSessionFactory build(InputStream inputStream, Properties properties)
SqlSessionFactory build(InputStream inputStream, String environment, Properties props)
SqlSessionFactory build(Configuration config)
注意:我们看下每个参数具体做什么?
- reader/inputStream 很简单就是
mybatis-config.xml的字符流/字节流信息 - environment 默认的环境变量Id
- properties 自定义属性信息,优先级最高
我们继续向下看,build(InputStream inputStream, String environment, Properties props)的实现
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 {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
从代码看mybatis-config.xml交给了XMLConfigBuilder来解析最终返回一个Configuration,也就是Configuration里存在mybatis-config.xml配置中所有信息,最终通过SqlSessionFactory build(Configuration config)返回我们需要的SqlSessionFactory,也就是DefaultSqlSessionFactory
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
当然,我们也可以不通过xml配置,自己实现Configuration类,实现创建SqlSessionFactory
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
下一章我们解析XMLConfigBuilder是怎么解析mybatis-config.xml