1.通过调试,session调用的getMapper是其实现类DefaultSQLSession中的

        //1.读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建 SqlSessionFactory 的构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.使用构建者创建工厂对象 SqlSessionFactory
SqlSessionFactory factory = builder.build(in);
//4.使用 SqlSessionFactory 生产 SqlSession 对象
SqlSession session = factory.openSession();
//5.使用 SqlSession 创建 dao 接口的代理对象
IBookDao bookDao = session.getMapper(IBookDao.class);
//6.使用代理对象执行查询所有方法
List<Book> books = bookDao.selectAll();
for (Book book : books) {
System.out.println(book);
}
//7.释放资源
session.close();
in.close();

2.在DefaultSQLSession类中getMapper方法如下,里面调用Configuration类的泛型方法<T> T getMapper(Class<T> type)

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

3.在Configuration类中查看getMapper(type, sqlSession)方法,里面调用的是MapperRegistry类里面的getMapper(type, sqlSession)方法。

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

4.进入MapperRegistry类里面查看getMapper(type, sqlSession)方法。里面通过属性knownMappers里面的方法get(Object key)获取MapperProxyFactory<T>泛型类,使用这个类里面的newInstance(SqlSession sqlSession)方法。

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

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

5.进入MapperProxyFactory<T>泛型类,查看newInstance(SqlSession sqlSession)方法如下;这里面生成一个MapperProxy<T>对象mapperProxy,然后使用T newInstance(MapperProxy<T> mapperProxy)实现动态代理。其中MapperProxy<T>类实现了接口InvocationHandler。重写了Object invoke(Object proxy, Method method, Object[] args)方法

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

6.查看MapperProxy<T>类里的invoke方法.

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try { if (Object.class.equals(method.getDeclaringClass())) {//并不是每个方法都需要调用代理对象进行执行,如果这个方法是Object中通用的方法,则无需执行
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {//判断是不是接口默认方法,1.8之后接口就有默认方法了
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//从缓存中获取MapperMethod对象,如果缓存中没有,则创建一个,并添加到缓存中
final MapperMethod mapperMethod = cachedMapperMethod(method);
// 执行方法对应的 SQL 语句
return mapperMethod.execute(sqlSession, args);
}

7.查看MapperMethod 类的execute方法,这个方法是执行sql的主要方法,根据我写的程序这里是调用executeForMany方法,实际上这个方法DefaultSqlSession类里面的selectList方法。

 public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
//insert语句的处理逻辑
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
//update语句的处理逻辑
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
//delete语句的处理逻辑
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
//select语句的处理逻辑
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;
}

private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
} else {
result = sqlSession.<E>selectList(command.getName(), param);
}
// issue #510 Collections & arrays support
if (!method.getReturnType().isAssignableFrom(result.getClass())) {
if (method.getReturnType().isArray()) {
return convertToArray(result);
} else {
return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
}
}
return result;
}

在这里,动态代理过程就完成了。大致执行过程是  sqlSession.getMapper()【这个sqlSession实际上是 DefaultSqlSession】-----调用---->Configuration.getMapper()-----调用--->MapperRegistry.getMapper() ------调用-->MapperProxyFactory.newInstance() -------调用----> Proxy.newProxyInstance()【其中的InvocationHandler接口由实现类MapperProxy代替】------invoke----->MapperMethod.execute()-----调用----->DefaultSqlSession.相应方法

Mybatis---01Mybatis动态代理过程分析的更多相关文章

  1. Mybatis mapper动态代理的原理详解

    在开始动态代理的原理讲解以前,我们先看一下集成mybatis以后dao层不使用动态代理以及使用动态代理的两种实现方式,通过对比我们自己实现dao层接口以及mybatis动态代理可以更加直观的展现出my ...

  2. (十二)mybatis之动态代理

    mybatis之动态代理的应用 在前文(https://www.cnblogs.com/NYfor2018/p/9093472.html)我们知道了,Mybatis的使用需要用到Mapper映射文件, ...

  3. MyBatis学习(三)MyBatis基于动态代理方式的增删改查

    1.前言 上一期讲到MyBatis-Statement版本的增删改查.可以发现.这种代码写下来冗余的地方特别多.写一套没啥.如果涉及到多表多查询的时候就容易出现问题.故.官方推荐了一种方法.即MyBa ...

  4. 【转载】由浅入深分析mybatis通过动态代理实现拦截器(插件)的原理

    转自:http://zhangbo-peipei-163-com.iteye.com/blog/2033832?utm_source=tuicool&utm_medium=referral 我 ...

  5. Mybatis使用动态代理实现拦截器功能

    1.背景介绍 拦截器顾名思义为拦截某个功能的一个武器,在众多框架中均有“拦截器”.这个Plugin有什么用呢?或者说拦截器有什么用呢?可以想想拦截器是怎么实现的.Plugin用到了Java中很重要的一 ...

  6. JAVA框架 Spring 和Mybatis整合(动态代理)

    一.使用传统方式的dao的书写方式,不建议.目前采用的是动态代理的方式交给mybatis进行处理. 首先回顾下动态代理要求: 1)子配置文件的中,namespace需要是接口的全路径,id是接口的方法 ...

  7. spring如何管理mybatis(一) ----- 动态代理接口

    问题来源 最近在集成spring和mybatis时遇到了很多问题,从网上查了也解决了,但是就是心里有点别扭,想看看到底怎么回事,所以跟了下源码,终于发现了其中的奥妙. 问题分析 首先我们来看看基本的配 ...

  8. Mybatis 之动态代理

    使用Mybatis 开发Web 工程时,通过Mapper 动态代理机制,可以只编写接口以及方法的定义. 如下: 定义db.properties driver=oracle.jdbc.OracleDri ...

  9. Spring 整合Mybatis Mapper动态代理方法

    先看项目目录结构 很清爽了 最重要的Spring的核心配置文件,看一下 <?xml version="1.0" encoding="UTF-8"?> ...

  10. Mybatis Mapper动态代理方式 typeAliases 别名的使用

    目录结构及配置文件与原始dao方法相比更简便 只需一个UserMapper的接口,放在一起的配置文件,配置文件中namespace的地址确定jdk动态代理的对象 <?xml version=&q ...

随机推荐

  1. Java Web学习(一)Web基础

    文章更新时间:2020/07/24 一.基本概念 web资源 Internet上供外界访问的Web资源分为两种: 静态web资源(如html 页面):指web页面中供人们浏览的数据始终是不变. 动态w ...

  2. day58:Linux:BashShell&linux文件管理&linux文件下载上传

    目录 1.BashShell 2.Linux文件管理 3.Linux文件下载和上传 BashShell 1.什么是BeshShell? 命令的解释,用来翻译用户输入的指令 2.BashShell能做什 ...

  3. Spring及tomcat初始化日志

    Tomcat StandardContext初始化过程 //org.apache.catalina.core.StandardContext#startInternal // 子容器启动 for (C ...

  4. springboot项目整合rabbitMq涉及消息的发送确认,消息的消费确认机制,延时队列的实现

    1.引入maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  5. IIS目录浏览模式打开文件还是无法下载

    写在前面的话 IIS已经设置目录浏览启用,且可以正常访问到文件,说明这些设置没问题,但是点击文件进行下载时,却提示无法下载,文件不存在等等,有的又可以,一顿操作后发现,原来是文件类型没有包含在MIME ...

  6. sqli-labs第一关 详解

    sqli-labs第一关 方法一:手工注入 方法二:sqlmap工具 两种方式,都可以学学,顺便学会用sqlmap,也是不错的.不多说,我们开始吧 方法一: 来到第一关,图上说我们需要一个数字的参数 ...

  7. JDK1.8新特性之(二)--方法引用

    在上一篇文章中我们介绍了JDK1.8的新特性有以下几项. 1.Lambda表达式 2.方法引用 3.函数式接口 4.默认方法 5.Stream 6.Optional类 7.Nashorm javasc ...

  8. 使用 Aria2 代替迅雷

    一.原因 迅雷下载速度一般,thunder:// 开头的链接也逐渐被 bt 链接替代. 迅雷很流氓,安装后 (尤其是 Windows 系统) 浏览器默认使用迅雷下载,对于小文件来说使用浏览器内置下载可 ...

  9. puts()和gets()函数

    puts()和gets()函数 1. puts()函数 puts()函数用来向标准输出设备(屏幕)写字符串并换行, 其调用格式为: puts(s); 其中s为字符串变量(字符串数组名或字符串指针). ...

  10. [POI2005]SAM-Toy Cars 贪心+堆

    [POI2005]SAM-Toy Cars 题目:Jasio 是一个三岁的小男孩,他最喜欢玩玩具了,他有n 个不同的玩具,它们都被放在了很高的架子上所以Jasio 拿不到它们:为了让他的房间有足够的空 ...