mybatis的源码应该算是比较容易阅读的,首先mybatis核心功能就是执行Sql语句,但在其基础上又有许多加强的地方(动态Sql,ORM等)。看一个框架的时候,第一步是对整个框架有一个大致的了解。例如mybatis,咱们能够从初始化到完成一个sql请求为主线,看一下涉及了哪些类。我我的总结了一下,mybatis的框架主要的核心类有4个 html
Configuration就是用于解析、保存、处理Mybatis的配置内容,包括了java
总结Configuration的功能,固然,如何读取和解析相关文件是Configuration中大部分代码作的事。这些都是为了准备后面mybatis运行的基本条件。Configuration中建立类是由于建立的这些类都依赖于Configuration(但这样作数据和逻辑没有作到分离)。sql
SqlSession多是mybatis中咱们最经常使用的类,其实他是一个门面类,直接对外提供服务数据库
public interface SqlSession extends Closeable { <T> T selectOne(String statement); <E> List<E> selectList(String statement, Object parameter); int delete(String statement); void rollback(); void commit(); ... }
这些方法都是直接提供给外部调用的。看到这些方法是否是很亲切。(我我的在看源码的时候看到一些本身用过的一些类或方法的时候都有种莫名的亲近感。感受终于和个人认知世界有交集了)缓存
SqlSessionFactor是用于建立SqlSession建造者,提供给外部快速建立一个SqlSession。是一个工厂类,而SqlSessionFactor的建立则是由SqlSessionFactorBuilder。 mybatis
前面说了SqlSession只是一个门面类,Executor才是负责Sql语句执行的。所以Executor才是整个mybatis核心。Executor的实现类有 架构
咱们看一个Executor参数最多的一个方法app
<E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;
这些类都对执行Sql有必定关系框架
具体点来理解就是咱们定义的Sql映射语句,例如咱们xml定义的:ide
<select id="selectCountByPath" parameterType="java.lang.String" resultType="java.lang.Long"> select count(1) FROM config WHERE path = #{path} </select>
这个就是传递给sql映射的参数,用于生成和填充动态sql语句
限定一次查询数据量,类很简单,看代码就明白,很少说
public class RowBounds { public static final int NO_ROW_OFFSET = 0; public static final int NO_ROW_LIMIT = Integer.MAX_VALUE; public static final RowBounds DEFAULT = new RowBounds(); private int offset; private int limit; public RowBounds() { this.offset = NO_ROW_OFFSET; this.limit = NO_ROW_LIMIT; } public RowBounds(int offset, int limit) { this.offset = offset; this.limit = limit; } }
这个和本地缓存有关,用于保存一个查询语句的缓存对象,下次有相同的查询语句的时候就会先尝试从本地缓存中获取。 注意:
一个查询语句的在本地缓存中的key,根据sql语句,参数等等组成
这个对象就是本次实际须要执行的sql语句有关的信息,
public class BoundSql { private String sql; private List<ParameterMapping> parameterMappings; private Object parameterObject; private Map<String, Object> additionalParameters; private MetaObject metaParameters; ...
若是说parameter参数是实际传入的参数,那么BoundSql就是根据传入参数进行相关解析后的结果。他的建立在MappedStatement中,根据parameter和当前执行MappedStatement生成
public BoundSql getBoundSql(Object parameterObject) { BoundSql boundSql = sqlSource.getBoundSql(parameterObject); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings == null || parameterMappings.isEmpty()) { boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject); } // check for nested result maps in parameter mappings (issue #30) for (ParameterMapping pm : boundSql.getParameterMappings()) { String rmId = pm.getResultMapId(); if (rmId != null) { ResultMap rm = configuration.getResultMap(rmId); if (rm != null) { hasNestedResultMaps |= rm.hasNestedResultMaps(); } } } return boundSql; }
Mybatis提供了Interceptor用于在执行Executor以前进行一些操做,mybatis是怎么使用Interceptor。其实就是在建立Executor时候,会
public Executor newExecutor(Transaction transaction, ExecutorType executorType) { executorType = executorType == null ? defaultExecutorType : executorType; executorType = executorType == null ? ExecutorType.SIMPLE : executorType; Executor executor; if (ExecutorType.BATCH == executorType) { executor = new BatchExecutor(this, transaction); } else if (ExecutorType.REUSE == executorType) { executor = new ReuseExecutor(this, transaction); } else { executor = new SimpleExecutor(this, transaction); } if (cacheEnabled) { executor = new CachingExecutor(executor); } //看这里!!! executor = (Executor) interceptorChain.pluginAll(executor); return executor; }
这里主要是经过jdk动态代理实现的
public class Plugin implements InvocationHandler { ... public static Object wrap(Object target, Interceptor interceptor) { Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); Class<?> type = target.getClass(); Class<?>[] interfaces = getAllInterfaces(type, signatureMap); if (interfaces.length > 0) { return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); } return target; } ... @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Set<Method> methods = signatureMap.get(method.getDeclaringClass()); if (methods != null && methods.contains(method)) { return interceptor.intercept(new Invocation(target, method, args)); } return method.invoke(target, args); } catch (Exception e) { throw ExceptionUtil.unwrapThrowable(e); } }
这样在调用Executor的时候就会先判断是否知足Interceptor的执行条件,知足则会先执行Intercepter#intercept()方法
要说直接和Jdbc打交道的就是各类Handler类,例如
上面的这些其实都不复杂,因此代码仍是比较好理解的
每一个Executor生成的时候都会把Transaction传入,在BaseExecutor中Transaction是其成员变量,那Transaction的做用是什么呢?
public interface Transaction { Connection getConnection() throws SQLException; void commit() throws SQLException; void rollback() throws SQLException; void close() throws SQLException; Integer getTimeout() throws SQLException; }
其实以前一直都没提到过Connect谁来管理,这里能够看出来,Transaction负责了Connection的获取,以及对此次Connect的提交和回滚等操做。这个类也是比较好理解的。Executor的commit或者rollback最后都是调用Transaction的
能够看出,mybatis的源码是比较容易阅读的(相对于Spring等)。上面介绍了框架中的一些核心类,可是不少细节的地方值得咱们去深挖。这个就须要咱们能沉下来好好阅读代码。