MyBatis框架是如何去执行SQL语句?相信不只是你们,笔者也想要知道是如何进行的。相信有上一章的引导大家都知道SqlSession接口的作用。当然默认情况下还是使用DefaultSqlSession类。关于SqlSession接口的用法有很多种。笔者还是比较喜欢用getMapper方法。对于getMapper方法的实现方式。笔者不能下一个定论。笔者只是想表示一下自己的理解而以——动态代理。

笔者把关于getMapper方法的实现方式理解为动态代理。事实上笔者还想说他可以是一个AOP思想的实现。那么具体是一个什么样子东西。相信笔者说了也不能代表什么。一切还是有大家自己去查看和理解。从源码上我们可以看到getMapper方法会去调用Configuration类的getMapper方法。好了。一切的开始都在这里了。

DefaultSqlSession类:

 public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}

对于Configuration类上一章里面就说明他里面存放了所有关于XML文件的配置信息。从参数上我们可以看到他要我们传入一个Class<T>类型。这已经可以看到后面一定要用到反射机制和动态生成相应的类实例。让我们进一步查看一下源码。

Configuration类:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}

当笔者点击进来发现他又调用MapperRegistry类的getMapper方法的时候,心里面有一种又恨又爱的冲动——这就是构架之美和复杂之恨。MapperRegistry类笔者把他理解存放动态代理工厂(MapperProxyFactory类)的库存。当然我们还是进去看一看源码吧。

MapperRegistry类:

  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}

好了。笔者相信大家看到这一段代码的时候都明白——MapperRegistry类就是用来存放MapperProxyFactory类的。我们还是在看一下knownMappers成员是一个什么要样子的集合类型。

private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

knownMappers是一个字典类型。从Key的类型上我们可以判断出来是一个类一个动态代理工厂。笔者看到这里的时候都会去点击一个MapperProxyFactory类的源码。看看他里面又是一些什么东东。

 public class MapperProxyFactory<T> {

   private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>(); public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
} public Class<T> getMapperInterface() {
return mapperInterface;
} public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
} @SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
} public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
} }

还好。代码不是很多,理解起来也不是很复杂。略看一下源码,笔者做了一个很大胆的猜测——一个类,一个动态代理工厂,多个方法代理。我们先把猜测放在这里,然后让我们回到上面部分吧。我们发现MapperRegistry类的getMapper方法里面最后会去调用MapperProxyFactory类的newInstance方法。这个时候我们又看到他实例化了一个MapperProxy类。MapperProxy类是什么。这个就关系到Proxy类的用法了。所以读者们自己去查看相关资料了。意思明显每执行一次XxxMapper(例如:笔者例子里面的IProductMapper接口)的方法都会创建一个MapperProxy类。方法执行之前都会先去调用相应MapperProxy类里面的invoke方法。如下

MapperProxy类:

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}

从源码的意思:从缓存中获得执行方法对应的MapperMethod类实例。如果MapperMethod类实例不存在的情况,创建加入缓存并返回相关的实例。最后调用MapperMethod类的execute方法。

到这里笔者小结一下,上面讲到笔者例子里面用到的getMapper方法。getMapper方法就是用来获得相关的数据操作类接口。而事实数据操作类邦定了动态代理。所以操据操作类执行方法的时候,会触动每个方法相应的MapperProxy类的invoke方法。所以invoke方法返回的结果就是操据操作类执行方法的结果。这样子我们就知道最后的任务交给了MapperMethod类实例。

MapperMethod类里面有俩个成员:SqlCommand类和MethodSignature类。从名字上我们大概的能想到一个可能跟SQL语句有关系,一个可能跟要执行的方法有关系。事实也是如此。笔者查看了SqlCommand类的源码。确切来讲这一部分的内容跟XxxMapper的XML配置文件里面的select节点、delete节点等有关。我们都会知道节点上有id属性值。那么MyBatis框架会把每一个节点(如:select节点、delete节点)生成一个MappedStatement类。要找到MappedStatement类就必须通过id来获得。有一个细节要注意:代码用到的id = 当前接口类 + XML文件的节点的ID属性。如下

 public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
String statementName = mapperInterface.getName() + "." + method.getName();
MappedStatement ms = null;
if (configuration.hasStatement(statementName)) {
ms = configuration.getMappedStatement(statementName);
} else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35
String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
if (configuration.hasStatement(parentStatementName)) {
ms = configuration.getMappedStatement(parentStatementName);
}
}
if (ms == null) {
if(method.getAnnotation(Flush.class) != null){
name = null;
type = SqlCommandType.FLUSH;
} else {
throw new BindingException("Invalid bound statement (not found): " + statementName);
}
} else {
name = ms.getId();
type = ms.getSqlCommandType();
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
}

看到这里的时候,我们就可以回头去找一找在什么时候增加了MappedStatement类。上面之所以可以执行是建立在XML配置信息都被加载进来了。所以MappedStatement类也一定是在加载配置的时候就进行的。请读者们自行查看一下MapperBuilderAssistant类的addMappedStatement方法——加深理解。SqlCommand类的name成员和type成员我们还是关注一下。name成员就是节点的ID,type成员表示查寻还是更新或是删除。至于MethodSignature类呢。他用于说明方法的一些信息,主要有返回信息。

笔者上面讲了这多一点主要是为了查看execute方法源码容易一点。因为execute方法都要用到SqlCommand类和MethodSignature类。

   public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}

重点部分就是这里,我们会发现我们转了一圈,最后还是要回到SqlSession接口实例上。完美的一圈!笔者用红色标出来了。

看到了这里我们就清楚调头去看一下SqlSession接口实例吧。

MyBatis 源码分析——动态代理的更多相关文章

  1. MyBatis 源码分析——动态SQL语句

    有几年开发经验的程序员应该都有暗骂过原生的SQL语句吧.因为他们不能一句就搞定一个业务,往往还要通过代码来拼接相关的SQL语句.相信大家会理解SQL里面的永真(1=1),永假(1=2)的意义吧.所以m ...

  2. MyBatis源码分析-SQL语句执行的完整流程

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  3. MyBatis源码分析(2)—— Plugin原理

    @(MyBatis)[Plugin] MyBatis源码分析--Plugin原理 Plugin原理 Plugin的实现采用了Java的动态代理,应用了责任链设计模式 InterceptorChain ...

  4. MyBatis 源码分析 - 插件机制

    1.简介 一般情况下,开源框架都会提供插件或其他形式的拓展点,供开发者自行拓展.这样的好处是显而易见的,一是增加了框架的灵活性.二是开发者可以结合实际需求,对框架进行拓展,使其能够更好的工作.以 My ...

  5. MyBatis 源码分析 - 映射文件解析过程

    1.简介 在上一篇文章中,我详细分析了 MyBatis 配置文件的解析过程.由于上一篇文章的篇幅比较大,加之映射文件解析过程也比较复杂的原因.所以我将映射文件解析过程的分析内容从上一篇文章中抽取出来, ...

  6. MyBatis 源码分析 - 配置文件解析过程

    * 本文速览 由于本篇文章篇幅比较大,所以这里拿出一节对本文进行快速概括.本篇文章对 MyBatis 配置文件中常用配置的解析过程进行了较为详细的介绍和分析,包括但不限于settings,typeAl ...

  7. MyBatis 源码分析系列文章导读

    1.本文速览 本篇文章是我为接下来的 MyBatis 源码分析系列文章写的一个导读文章.本篇文章从 MyBatis 是什么(what),为什么要使用(why),以及如何使用(how)等三个角度进行了说 ...

  8. Mybatis源码分析

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  9. MyBatis源码分析(各组件关系+底层原理

    MyBatis源码分析MyBatis流程图 下面将结合代码具体分析. MyBatis具体代码分析 SqlSessionFactoryBuilder根据XML文件流,或者Configuration类实例 ...

随机推荐

  1. EasyUI中dialog中嵌入form细节问题记录

    当代码如下: function myClear() { $("#add_form").form("reset"); $("#add_dialog&qu ...

  2. (中等) CF 555E Case of Computer Network,双连通+树。

    Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible a ...

  3. 导出WAS已部署的ear包的几种方法

    可以通过下面几种办法将部署好的工程导出为一个ear包. 1.最简单的,通过was的控制台导出: 首先登录控制台,进入"企业应用程序"管理页面,选中要导出的工程,点击"导出 ...

  4. openstack controller ha测试环境搭建记录(一)——操作系统准备

    为了初步了解openstack controller ha的工作原理,搭建测试环境进行学习. 在学习该方面知识时,当前采用的操作系统版本是centos 7.1 x64.首先在ESXi中建立2台用于测试 ...

  5. mongodb 分片群集(sharding cluster)

    实际环境架构 分别在3台机器运行一个mongod实例(称为mongod shard11,mongod shard12,mongod shard13)组织replica set1,作为cluster的s ...

  6. (中等) HDU 2295 , DLX+重复覆盖+二分。

    Description N cities of the Java Kingdom need to be covered by radars for being in a state of war. S ...

  7. Arduino单片机使用和开发问题记录(转)

    源:Arduino单片机使用和开发问题记录 1.将程序上传到板子时Arduino IDE提示“avrdude: stk500_getsync(): not in sync: resp=0x00” 网上 ...

  8. Sublime Text 2快捷键大全

    作者:zccst 2015-04-13 Sublime 插件安装 http://www.cnblogs.com/jingwhale/p/4421021.html 2014-09-17 Sublime ...

  9. iOS动画特效

    关于图层的几个坐标系. 对于ios来说,坐标系的(0,0)点在左上角,就是越往下,Y值越大.越往右,X值越大. 一个图层的frame,它是position,bounds,anchorPoint和tra ...

  10. EF的join用法

    var customers = DB.Customer.Join(DB.Commission, cst => cst.CommissionId,                          ...