楔子
之前用了很久的mybatis,但是从来没有去认真的看过它的源代码,于是便产生的阅读mybatis源代码的念头。无论做什么事,开始的着手点是最难的。对于阅读源代码,最好的方式无外乎写一下小的case,然后一步一步debug跟进。但是由mybatis源代码中提供完善的单元测试,因此我们可以不必自己去写case,直接使用这些单元测试就可以了。
例如:使用mybatis简单的执行一条SQL就可以通过SqlSessionTest这个test suit来了解,mybatis会:
- 创建data source,读取配置文件,创建session manager
@BeforeClass public static void setup() throws Exception { createBlogDataSource(); final String resource = "org/apache/ibatis/builder/MapperConfig.xml"; final Reader reader = Resources.getResourceAsReader(resource); sqlMapper = new SqlSessionFactoryBuilder().build(reader); }
- 打开session,执行sql,完成后关闭session
@Test public void shouldSelectCountOfPosts() throws Exception { SqlSession session = sqlMapper.openSession(); try { Integer count = session.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectCountOfPosts"); assertEquals(5, count.intValue()); } finally { session.close(); }
以上就是mybatis如果执行简单的sql。
我们可以看到,mybatis首先会通过读取配置创初始化环境。然后在执行SQL的时候,首先回去打开一个session,执行完SQL之后,会关闭session。对于环境的初始化,我们在下一节在看,首先我们来看session的创建。
Session Factory
从上面的代码,我们可以看到,mybatis会通过读取配置文件创建一个session factory,这里使用了抽象工厂的模式,session factory是一个interface,
public interface SqlSessionFactory {
SqlSession openSession();
SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType, Connection connection);
Configuration getConfiguration();
}
openSession方法会返回一个SqlSession。同样SqlSession也只是一个继承了Closeable接口。
public interface SqlSession extends Closeable
mybatis通过两个SqlSessionFactory的实现
- DefaultSqlSessionFactory
- SqlSessionManager
与之相应的有两个SqlSession的实现 - DefaultSqlSession
- SqlSessionManager
在我们的test case中,mybatis使用的是DefaultSqlSessionFactory,所以我们来看DefaultSqlSessionFactory。在DefaultSqlSessionFactory中,有两种方式来open session,
一种是通过datasource来创建transaction,一种是通过connect创建。同时两种方式都会根据configuration创建executer,以及transaction的commit方式,然后以参数形式维护到sql session中。同样的两种方式最终都是指向JdbcTransaction,回归到最根本的jdbc transaction。
上面的就是我们mybatis源码阅读的开始,下来我们将学习mybatis如何读取配置初始化环境。
网友评论