Mybatis源码解析之mapper接口的代理模式详解

 更新时间:2023年12月25日 11:47:43   作者:二狗家有矿  
这篇文章主要介绍了Mybatis源码解析之mapper接口的代理模式详解,在mybatis中执行sql时有两种方式,一种是基于statementId,也就是直接调用SqlSession的方法,需要的朋友可以参考下

一、简介

在mybatis中执行sql时有两种方式,一种是基于statementId,也就是直接调用SqlSession的方法,如sqlSession.update(“statementId”); 还有一种方法是基于java接口,也是日常开发中最常用的方式。 mapper接口中的每个方法都可以喝mapper xml中的一条sql语句对应,我们可以直接通过调用接口方法的方式进行sql执行。因为mybatis会为mapper接口通过jdk动态代理的方法生成接口的实现类,本篇文章将针对mapper接口的代理展开分析。 以下是mapper接口的代理模式的核心组件的类图。

Mapper代理模式类图

二、MapperRegistry

MapperRegistry通过Map结构的属性knownMappers中维护着mybatis中所有的mapper接口。

1. MapperRegistry#addMapper(class)

当开发者在配置文件中配置了通过mappers节点的子节点mapper配置了mapper接口时,会调用configuation#addMapper(Class)记录mapper接口,而configuration又委托了MapperRegistry#addMapper(class)处理逻辑。

public <T> void addMapper(Class<T> type) {
  if (type.isInterface()) {
    if (hasMapper(type)) {
      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
    }
    boolean loadCompleted = false;
    try {
      knownMappers.put(type, new MapperProxyFactory<T>(type));
      // It's important that the type is added before the parser is run
      // otherwise the binding may automatically be attempted by the
      // mapper parser. If the type is already known, it won't try.
      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
      parser.parse();
      loadCompleted = true;
    } finally {
      if (!loadCompleted) {
        knownMappers.remove(type);
      }
    }
  }
}

可以看到,MapperRegistry以mapper接口的类型为key值,将接口类型封装成MapperProxyFactory作为value值放入knownMappers。

2. MapperRegistry#getMapper(Class, SqlSession)

该方法基于SqlSession参数向外提供了对应类型的mapper接口的对象。

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);
  }
}

根据mapper接口类型找到对应的MapperProxyFactory时,调用其newInstance方法得到对应的对象返回。

三、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);
  }
}

如果对jdk动态代理有一定了解,很容易就能看出来MapperProxyFactory的newInstance方法是很典型的生成代理对象的方式。

四、MapperProxy

MapperProxy作为InvocationHandler的实现类,是jdk动态代理模式的核心。

1. MapperProxy#invoke(Object, Method, Object[])

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
    if (Object.class.equals(method.getDeclaringClass())) {
      return method.invoke(this, args);
    } else if (isDefaultMethod(method)) {
      return invokeDefaultMethod(proxy, method, args);
    }
  } catch (Throwable t) {
    throw ExceptionUtil.unwrapThrowable(t);
  }
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
}
 
private MapperMethod cachedMapperMethod(Method method) {
  MapperMethod mapperMethod = methodCache.get(method);
  if (mapperMethod == null) {
    mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
    methodCache.put(method, mapperMethod);
  }
  return mapperMethod;
}

对于Object方法和default方法,执行原方法逻辑即可。 对于对于sql语句的方法,交给MapperMethod 处理。

五、MapperMethod

Mapper类负责去处理mapper接口中的sql方法。

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;
}

MapperMethod还有一个静态内部类MethodSignature用作mapper方法的标签,SqlCommand用作sql命令。 可以看到,根据sql命令的类型(insert|update|delete|select|flush)和返回类型分别调用SqlSession的不同方法,然后对insert|update|delete方法的返回值做适配。

MapperMethod#rowCountResult(int)

private Object rowCountResult(int rowCount) {
 final Object result;
  if (method.returnsVoid()) {
    result = null;
  } else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
    result = rowCount;
  } else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
    result = (long)rowCount;
  } else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
    result = rowCount > 0;
  } else {
    throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
  }
  return result;
}

insert|update|delete方法方法的返回值就是sql命令的匹配行数,而在mapper方法中支持Integer、Long、Boolean和void类型的返回,因此做简单适配。

到此这篇关于Mybatis源码解析之mapper接口的代理模式详解的文章就介绍到这了,更多相关mapper接口的代理模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java数据结构基础:绪论

    java数据结构基础:绪论

    这篇文章主要介绍了Java的数据解构基础,希望对广大的程序爱好者有所帮助,同时祝大家有一个好成绩,需要的朋友可以参考下,希望能给你带来帮助
    2021-07-07
  • java中栈和队列的实现和API的用法(详解)

    java中栈和队列的实现和API的用法(详解)

    下面小编就为大家带来一篇java中栈和队列的实现和API的用法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • SpringBoot整合Dozer映射框架流程详解

    SpringBoot整合Dozer映射框架流程详解

    dozer是用来两个对象之间属性转换的工具,有了这个工具之后,我们将一个对象的所有属性值转给另一个对象时,就不需要再去写重复的set和get方法了,下面介绍下SpringBoot中Dozer的使用,感兴趣的朋友一起看看吧
    2022-07-07
  • Java将Word文件转为OFD文件

    Java将Word文件转为OFD文件

    大家好,本篇文章主要讲的是Java将Word文件转为OFD文件,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2021-12-12
  • Java的JSON格式转换库GSON的初步使用笔记

    Java的JSON格式转换库GSON的初步使用笔记

    GSON是Google开发并在在GitHub上开源的Java对象与JSON互转功能类库,在Android开发者中也大受欢迎,这里我们就来看一下Java的JSON格式转换库GSON的初步使用笔记:
    2016-06-06
  • Java 排序算法整合(冒泡,快速,希尔,拓扑,归并)

    Java 排序算法整合(冒泡,快速,希尔,拓扑,归并)

    这篇文章主要介绍了Java 排序算法整合(冒泡,快速,希尔,拓扑,归并),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Mybatis配置之<properties>属性配置元素解析

    Mybatis配置之<properties>属性配置元素解析

    这篇文章主要介绍了Mybatis配置之<properties>属性配置元素解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 如何使用IDEA的groovy脚本文件生成带JPA注解的实体类(图文详解)

    如何使用IDEA的groovy脚本文件生成带JPA注解的实体类(图文详解)

    这篇文章主要介绍了如何使用IDEA的groovy脚本文件生成带JPA注解的实体类,本文通过图文并茂实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • idea鼠标控制放大缩小的操作

    idea鼠标控制放大缩小的操作

    这篇文章主要介绍了idea鼠标控制放大缩小的操作教程,具有很好的参考价值,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • SpringBoot实现对Http接口进行监控的代码

    SpringBoot实现对Http接口进行监控的代码

    Spring Boot Actuator是Spring Boot提供的一个模块,用于监控和管理Spring Boot应用程序的运行时信息,本文将介绍一下Spring Boot Actuator以及代码示例,以及如何进行接口请求监控,需要的朋友可以参考下
    2024-07-07

最新评论