MyBatis 中 Mapper 接口的使用原理

MyBatis 3 推荐使用 Mapper 接口的方式来执行 xml 配置中的 SQL,用起来很方便,也很灵活。在方便之余,想了解一下这是如何实现的,之前也大致知道是通过 JDK 的动态代理做到的,但这次想知道细节。

东西越多就越复杂,所以就以一个简单的仅依赖 MyBatis 3.4.0 的 CRUD 来逐步了解 Mapper 接口的调用。

通常是通过 xml 配置文件来创建SqlSessionFactory对象,然后再获取SqlSession对象,接着获取自定义的 Mapper 接口的代理对象,最后调用接口方法,示例如下:

/**
*
* @author xi
* @date 2018/10/01 14:12
*/
public class Demo {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = roleMapper.getRole(1L);
System.out.println(role);
}
}

如何解析配置文件,创建工厂,获取会话皆不是本次关注的重点,直接看下面这行即可:

RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);

获取自定义 Mapper 代理对象的方法位于:org.apache.ibatis.session.SqlSession#getMapper,还是个范型方法

  /**
* Retrieves a mapper.
* @param <T> the mapper type
* @param type Mapper interface class
* @return a mapper bound to this SqlSession
*/
<T> T getMapper(Class<T> type);

实现该方法的子类有:DefaultSqlSessionSqlSessionManager,这里关注默认实现即可:org.apache.ibatis.session.defaults.DefaultSqlSession#getMapper

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

这里面出现了 Configuration 对象,简单来说就是包含了 xml 配置解析内容的对象,同样它也不是现在关注的重点,继续往下跟进:org.apache.ibatis.session.Configuration#getMapper

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

这里出现了MapperRegistry对象,它是解析 Mapper.xml 中的内容(mapper标签中的namespace就包含了 Mapper 接口的全限定名称)得来的,含有一个 HashMap 类型的成员变量org.apache.ibatis.binding.MapperRegistry#knownMappers,key 是 Mapper 接口的Class对象,value 是org.apache.ibatis.binding.MapperProxyFactory,从名称就可以看出是用来创建 Mapper 接口的代理对象的工厂,后面会用到。

具体这个knownMappers是怎么填充的,详见org.apache.ibatis.binding.MapperRegistry#addMapper方法,暂时不管,先往下走:org.apache.ibatis.binding.MapperRegistry#getMapper

  @SuppressWarnings("unchecked")
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 接口的类型,从knownMappers中拿到对应的工厂,然后创建代理对象,继续跟进:org.apache.ibatis.binding.MapperProxyFactory#newInstance(org.apache.ibatis.session.SqlSession)

  public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}

这里又出现了一个MapperProxy对象,理解起来是一个代理对象,打开一看它实现了java.lang.reflect.InvocationHandler接口,这是挂羊头卖狗肉哇。

先不看狗肉了,继续跟进:org.apache.ibatis.binding.MapperProxyFactory#newInstance(org.apache.ibatis.binding.MapperProxy<T>)

  @SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}

在这,看到了熟悉的java.lang.reflect.Proxy,这里的mapperInterface是创建工厂时传入的 Mapper 接口。真正的 Mapper 接口的代理对象此时才产生,是真羊头。

这不是既熟悉又陌生的 JDK 动态代理么,说它熟悉,因为前面的狗肉mapperProxy是一个InvocationHandler对象,它拦截了所有对代理对象接口方法的调用。说它陌生是因为之前使用 JDK 动态代理时会有接口的具体实现子类,这里没看到。因为 MyBatis 只需要拦截接口方法,找到方法对应的 SQL 去执行就可以了,没必要多此一举加上实现子类,这也正是 MyBatis 方便的地方。接下来看看org.apache.ibatis.binding.MapperProxy

/**
* @author Clinton Begin
* @author Eduardo Macarron
*/
public class MapperProxy<T> implements InvocationHandler, Serializable { private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache; public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 判断 method 是不是 Object 类的方法,如 hashCode()、toString()
if (Object.class.equals(method.getDeclaringClass())) {
try {// 如果是,则调用当前 MapperProxy 对象的这些方法
// 跟 Mapper 接口的代理对象没关系
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
// 到这了,说明调用的是接口中的方法,具体的执行就不是本次关注的重点了
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
} // 对 MapperMethod 做了缓存,这个 methodCache 是个 ConcurrentHashMap,在 MapperProxyFactory 中创建的
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;
} }

具体说明都在代码注释里面,没啥好说的了。

总结

  1. 通过 JDK 动态代理模式,创建 Mapper 接口的代理对象,拦截对接口方法的调用;
  2. Mapper 接口中不能使用重载,具体原因参见org.apache.ibatis.binding.MapperMethod.SqlCommand#SqlCommand,MyBatis 是通过mapperInterface.getName() + "." + method.getName()去获取 xml 中解析出来的 SQL 的,具体可能还要看一下org.apache.ibatis.session.Configuration#mappedStatements

最后的最后,古话说的好:遇事不决,先开大龙(看源码)(逃

MyBatis 中 Mapper 接口的使用原理的更多相关文章

  1. mybatis中mapper接口的参数设置几种方法

    方法一:忽略parameterType,加@param("xxx")注解 在mapper接口中加上@param("xxx")注解,则在配置文件中直接用即可 Li ...

  2. 逆向工程生成的mybatis中mapper文件。mapper接口,实例化成对象

    逆向工程生成的mybatis中mapper文件中,*mapper文件只是接口,而不是类文件.但是却可以通过spring的容器获得实例. 例如: //1.获得mapper代理对象,从spring容器获得 ...

  3. mybatis从mapper接口跳转到相应的xml文件的eclipse插件

    mybatis从mapper接口跳转到相应的xml文件的eclipse插件 前提条件 开发软件 eclipse 使用框架 mybatis 为了方便阅读源码,项目使用mybatis的时候,方便从mapp ...

  4. Mybatis的Mapper接口方法不能重载

    今天给项目的数据字典查询添加通用方法,发现里边已经有了一个查询所有数据字典的方法 List<Dict> selectDictList(); 但我想设置的方法是根据数据字典的code查询出所 ...

  5. 5.7 Liquibase:与具体数据库独立的追踪、管理和应用数据库Scheme变化的工具。-mybatis-generator将数据库表反向生成对应的实体类及基于mybatis的mapper接口和xml映射文件(类似代码生成器)

    一. liquibase 使用说明 功能概述:通过xml文件规范化维护数据库表结构及初始化数据. 1.配置不同环境下的数据库信息 (1)创建不同环境的数据库. (2)在resource/liquiba ...

  6. IntelliJ IDEA中Mapper接口通过@Autowired注入报错的正确解决方式

    转载请注明来源:四个空格 » IntelliJ IDEA中Mapper接口通过@Autowired注入报错的正确解决方式: 环境 ideaIU-2018.3.4.win: 错误提示: Could no ...

  7. Mybatis中dao接口和mapper 的加载过程

    这里考虑的是mybatis和spring整合的场景 1.在系统启动的时候,会去执行配置文件中有关扫描mybatis接口的配置:通过MapperScannerConfigurer扫描接口生成spring ...

  8. Mybatis的mapper接口在Spring中实例化过程

    在spring中使用mybatis时一般有下面的配置 <bean id="mapperScannerConfigurer" class="org.mybatis.s ...

  9. Mybatis的mapper接口接受的参数类型

    最近项目用到了Mybatis,学一下记下来. Mybatis的Mapper文件中的select.insert.update.delete元素中有一个parameterType属性,用于对应的mappe ...

随机推荐

  1. vue-cli项目引入jquery和bootstrap

    1.安装插件 npm install jquery --save npm install bootstrap --save npm install popper.js --save //提示框插件,b ...

  2. Android布局管理器-从实例入手学习相对布局管理器的使用

    场景 AndroidStudio跑起来第一个App时新手遇到的那些坑: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103797 ...

  3. 「Flink」使用Managed Keyed State实现计数窗口功能

    先上代码: public class WordCountKeyedState { public static void main(String[] args) throws Exception { S ...

  4. vue2.0嵌套组件之间的通信($refs,props,$emit)

    vue的一大特色就是组件化,所以组件之间的数据交互是非常重要,而我们经常使用组件之间的通信的方法有:props,$refs和emit. 初识组件之间的通信的属性和方法 props的使用 子组件使用父组 ...

  5. Dalvik虚拟机和Art虚拟机

    Dalvik虚拟机 DVM是Dalvik Virtual Machine的缩写,是Android4.4及以前使用的虚拟机,所有android程序都运行在android系统进程里,每个进程对应着一个Da ...

  6. 清北学堂—2020.1提高储备营—Day 4 afternoon(动态规划初步(一))

    qbxt Day 4 afternoon --2020.1.20 济南 主讲:顾霆枫 目录一览 1.动态规划初步 2.记忆化搜索 3.递推式动态规划 4.记忆话搜索与递推式动态规划的转化 5.状态转移 ...

  7. 浅谈mysql触发器

    什么是触发器?简单的说,就是一张表发生了某件事(插入.删除.更新操作),然后自动触发了预先编写好的若干条SQL语句的执行.触发器本质也是存储过程,只是不需要手动调用,触发某事件时自动调用.触发器里的S ...

  8. Html介绍,认识html标签

    什么是网页?网页就是我们我们提前写好的代码样式经过浏览器的渲染展示出来的样式效果.其实我们常说的上网就是浏览各式各样的网页,这些网页都是由html标签组成,下面就是一个简单的网页,效果图如下: 简单看 ...

  9. iptables技术入门

    1- 概述 ___ netfilter/iptables: IP 信息包过滤系统,实际由两个组件netfilter和iptable组成.可以对流入和流出服务器的数据包进行很惊喜的控制.主要工作在OSI ...

  10. javaScript 数据类型,变量的类型转换,typeof()可以判断变量类型

    js的数据类型和常见隐式转化逻辑. 一.六种数据类型 原始类型(基本类型):按值访问,可以操作保存在变量中实际的值.原始类型汇总中null和undefined比较特殊. 引用类型:引用类型的值是保存在 ...