MyBatis源码阅读-总索引
构造器
public SqlSessionFactoryBuilder() {
}
build 方法创建SqlSessionFactory
//Reader 字符流
public SqlSessionFactory build(Reader reader) {
return this.build((Reader)reader, (String)null, (Properties)null);
}
public SqlSessionFactory build(Reader reader, String environment) {
return this.build((Reader)reader, environment, (Properties)null);
}
public SqlSessionFactory build(Reader reader, Properties properties) {
return this.build((Reader)reader, (String)null, properties);
}
//InputStream 字节流
public SqlSessionFactory build(InputStream inputStream) {
return this.build((InputStream)inputStream, (String)null, (Properties)null);
}
public SqlSessionFactory build(InputStream inputStream, String environment) {
return this.build((InputStream)inputStream, environment, (Properties)null);
}
public SqlSessionFactory build(InputStream inputStream, Properties properties) {
return this.build((InputStream)inputStream, (String)null, properties);
}
可以看到,上面最终都是调用下面的方法
//reader : 配置文件字符流
//environment : 配置文件中的environment id
//properties :
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
SqlSessionFactory var5;
try {
//解析配置文件
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
//通过配置信息创建SqlSessionFactory
//parser.parse() 返回的是Configuration对象
var5 = this.build(parser.parse());
} catch (Exception var14) {
throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException var13) { ;
}
}
return var5;
}
//inputStream : 配置文件字节流
//environment : 配置文件中的environment id
//properties :
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
SqlSessionFactory var5;
try {
//解析配置文件
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
//通过配置信息创建SqlSessionFactory
//parser.parse() 返回的是Configuration对象
var5 = this.build(parser.parse());
} catch (Exception var14) {
throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException var13) {
;
}
}
return var5;
}
通过配置信息创建SqlSessionFactory
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
读取配置文件,从上面build方法可知,参数可以为Reader或者InputStream对象。
通过Resources类来读取配置文件
//Resources是org.apache.ibatis.io.Resources类
//mybatis-config.xml存放在resource目录下,如果是放在resource/config,就写成"configure/mybatis-config.xml"
//读取为字符流
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//读取为字节流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
通过io流创建SqlSessionFactory
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);