mybatis源码阅读(1)

2017-02-22  本文已影响0人  路痴小僧

楔子

之前用了很久的mybatis,但是从来没有去认真的看过它的源代码,于是便产生的阅读mybatis源代码的念头。无论做什么事,开始的着手点是最难的。对于阅读源代码,最好的方式无外乎写一下小的case,然后一步一步debug跟进。但是由mybatis源代码中提供完善的单元测试,因此我们可以不必自己去写case,直接使用这些单元测试就可以了。

例如:使用mybatis简单的执行一条SQL就可以通过SqlSessionTest这个test suit来了解,mybatis会:

以上就是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的实现

上面的就是我们mybatis源码阅读的开始,下来我们将学习mybatis如何读取配置初始化环境。

上一篇 下一篇

猜你喜欢

热点阅读