session包是整个mybatis应用的对外接口包。
1.SqlSession及其相关类
1.1 SqlSession的生成链
在进行查询操作时,只需要和SqlSession对象打交道,而SqlSession对象是由SqlSessionFactory生产出来的,而SqlSessionFactory又是由SqlSessionFactoryBuilder创建的。
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
public SqlSessionFactory build(Reader reader, String environment) {
return build(reader, environment, null);
}
public SqlSessionFactory build(Reader reader, Properties properties) {
return build(reader, null, properties);
}
/**
* 建造一个SqlSessionFactory对象
* @param reader 读取字符流的抽象类
* @param environment 环境信息
* @param properties 配置信息
* @return SqlSessionFactory对象
*/
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
// 传入配置文件,创建一个XMLConfigBuilder类
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
// 分两步:
// 1、解析配置文件,得到配置文件对应的Configuration对象
// 2、根据Configuration对象,获得一个DefaultSqlSessionFactory
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
}
}
}
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment) {
return build(inputStream, environment, null);
}
public SqlSessionFactory build(InputStream inputStream, Properties properties) {
return build(inputStream, null, properties);
}
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) {
}
}
}
/**
* 根据配置信息建造一个SqlSessionFactory对象
* @param config 配置信息
* @return SqlSessionFactory对象
*/
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
}
DefaultSqlSessionFactory对象可以创建出SqlSession的子类DefualtSqlSession类的对象,该过程由openSessionFromDataSourcce方法完成。
/**
* 从数据源中获取SqlSession对象
* @param execType 执行器类型
* @param level 事务隔离级别
* @param autoCommit 是否自动提交事务
* @return SqlSession对象
*/
private SqlSession openSessionFromDataSource(