mybatis源码专题(二)
1)什么是SqlSession
SqlSession是实现与数据库进行会话的入口对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("classpath:mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
2)SqlSession对象应用过程分析
1、由于我们通过上面拿到的SqlSessionFactory的实例对象是DefaultSqlSessionFactory,所以我们通过该factory创建出来的SqlSession实例对象是DefaultSqlSession
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
2、通过DefaultSqlSession我们知道其里面包含一个configuration对象,configuration对象以Map集合的方式存储了所有MappedStatement对象,通过namespace+id就可以命中相应的MappedStatement对象,然后交由executor去处理
try {
//statement位命名空间namespace+id
MappedStatement ms = configuration.getMappedStatement(statement);
//命中namespace+id对应的MappedStatement 对象,交由executor去处理
//对于程序创建什么类型的executor,可配置
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
3、在Executor中利用MappedStatement的实例对象获取对应的Configuration,在通过Configuration创建对应的StatementHandler对象
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
4、在StatementHandler中分别对入参的处理和结果集的映射
parameterHandler.setParameters(statement);
resultSetHandler.<E> handleResultSets(statement);
3)SqlSession应用方式
方式一:通过命名空间namespace+id直接命中MappedStatement对象
方式二:通过sqlSession的getMapper(Class type)函数创建一个代理对象(这种方式实际开发中用的多)
分析
方式一所命中MappedStatement对象的key是通过mapper.xml文件中的namespace+id获得,而方法二是通过接口的包名+方法名去命中对应的MappedStatement对象,通过getMapper函数生成一个代理类,我们通过调用该代理类的方式就可以做出对用的操作,可以说方式二是在方式一的基础上做了一下底层封装,方便我们日常开发,但是性能上来看,方式一毫无争议是要比方式二高