MyBatis的Mapper代理原理

Cadence OrCAD: 层次化设计 Hierarchical Design 详细介绍OrCAD的原理图层次化设计方法。 阅读详情

Mapper代理模式产生的原因:
由于使用MyBatis框架时Mapper接口实现类中存在代码重复,整个操作过程模板重复(加载配置文件/创建SqlSessionFactory/生产SqlSession),故MyBatis推出了基于JDK动态代理自动生成代理Mapper接口实现类,代理类可以完成Mapper中定义的增删改查操作,避免代码重复工作。

MapperRegistry加载原理

在调用SqlSession.getMapper()方法时可以发现底层调用的是mapperRegistry.getMapper(type, sqlSession);那MapperRegistry又是什么呢?MapperRegistry封装了全局配置文件Configuration和
Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap();
knownMappers 的key是全部加载的Mapper接口,value是每个Mapper接口对于的代理类生成工厂。下面看看MapperRegistry是如何加载的:

1.进入XMLConfigBuilder的mapperXML解析方法mapperElement(XNode parent)方法,在mapper标签为package或者class格式是配置的为Mapper接口的包路径或Mapper接口的全限定名

private void mapperElement(XNode parent) throws Exception {
        if (parent != null) {
            Iterator var2 = parent.getChildren().iterator();

            while(true) {
                while(var2.hasNext()) {
                    XNode child = (XNode)var2.next();
                    String resource;
                    if ("package".equals(child.getName())) {
                        resource = child.getStringAttribute("name");
                        // 扫描Mapper接口方法   
                        this.configuration.addMappers(resource);
                    } else {
                        resource = child.getStringAttribute("resource");
                        String url = child.getStringAttribute("url");
                        String mapperClass = child.getStringAttribute("class");
                        XMLMapperBuilder mapperParser;
                        InputStream inputStream;
                        if (resource != null && url == null && mapperClass == null) {
                            ErrorContext.instance().resource(resource);
                            inputStream = Resources.getResourceAsStream(resource);
                            mapperParser = new XMLMapperBuilder(inputStream, this.configuration, resource, this.configuration.getSqlFragments());
                            mapperParser.parse();
                        } else if (resource == null && url != null && mapperClass == null) {
                            ErrorContext.instance().resource(url);
                            inputStream = Resources.getUrlAsStream(url);
                            mapperParser = new XMLMapperBuilder(inputStream, this.configuration, url, this.configuration.getSqlFragments());
                            mapperParser.parse();
                        } else {
                            if (resource != null || url != null || mapperClass == null) {
                                throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
                            }

                            Class<?> mapperInterface = Resources.classForName(mapperClass);
         // 扫描Mapper接口方法                   this.configuration.addMapper(mapperInterface);
                        }
                    }
                }

                return;
            }
        }
    }

2.进入configuration.addMapper(type)发现调用的是mapperRegistry.addMapper(type)

public <T> void addMapper(Class<T> type) {
		//判断是否是接口
        if (type.isInterface()) {
        	// 判断是否已经扫描过了
            if (this.hasMapper(type)) {
                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }

            boolean loadCompleted = false;

            try {
            	// 为当前Mapper接口创建代理类生成工厂
                this.knownMappers.put(type, new MapperProxyFactory(type));
                // 扫描当前Mapper接口中的注解,并解析后封装到核心配置类Configuration中
                MapperAnnotationBuilder parser = new MapperAnnotationBuilder(this.config, type);
                parser.parse();
                loadCompleted = true;
            } finally {
            // 如果解析注解过程中报错则剔除当前Mapper接口及其代理类生成工厂
                if (!loadCompleted) {
                    this.knownMappers.remove(type);
                }

            }
        }

    }

3.进入new MapperProxyFactory(type)代理类生成工厂的构造

	// mapper接口类型
 	private final Class<T> mapperInterface;
 	// 已执行方法缓存
    private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap();

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

总结:MapperRegistry在解析Mapper标签是初始化并封装

SqlSession.getMapper()方法原理

1.底层调用的mapperRegistry.getMapper(type, sqlSession);

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

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
            // 取到mapper对应的代理类生成工厂后,调用newInstance方法获取mapper代理类的实例
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }

2.进入newInstance(sqlSession);方法

MapperProxyFactory.class

private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap();

protected T newInstance(MapperProxy<T> mapperProxy) {
		//根据JDK动态代理生成mapper的代理类返回
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

  public T newInstance(SqlSession sqlSession) {
  		// MapperProxy实现了InvocationHandler接口的invoke
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        // 调用重载方法
        return this.newInstance(mapperProxy);
    }

代理类方法执行原理(invoke方法剖析)

1.进入MapperProxy类

MapperProxy.class


	// 当前调用getMapper方法的SqlSession
    private final SqlSession sqlSession;
    // 被执行方法所属Mapper接口的类型
    private final Class<T> mapperInterface;
    // 当前mapper已执行方法缓存
    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;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
	        // 被执行方法是否Object的方法如toString/equals等,如果是直接执行原方法
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            }
			//是否构造方法
            if (this.isDefaultMethod(method)) {
                return this.invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable var5) {
            throw ExceptionUtil.unwrapThrowable(var5);
        }
		// 获取当前方法相关参数
        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        // 执行execute方法
        return mapperMethod.execute(this.sqlSession, args);
    }

    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
            this.methodCache.put(method, mapperMethod);
        }

        return mapperMethod;
    }

2.进入mapperMethod.execute(this.sqlSession, args);方法,根据方法的相关参数及类型判断执行sqlSession的增删改查方法。

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

        if (result == null && this.method.getReturnType().isPrimitive() && !this.method.returnsVoid()) {
            throw new BindingException("Mapper method '" + this.command.getName() + " attempted to return null from a method with a primitive return type (" + this.method.getReturnType() + ").");
        } else {
            return result;
        }
    }```

RouterOS网桥VLAN实战:从零构建安全隔离的二层虚拟网络 本文详细讲解了如何在RouterOS上利用网桥和VLAN功能,从零开始构建安全隔离的二层虚拟网络。通过分步实战演示,涵盖核心概念、网桥创建、PVID设置、VLAN规则配置及安全过滤,帮助网络管理员实现办公、访客与服务器网络的逻辑隔离与灵活管理,提升网络安全性。 阅读详情

相关推荐

基于Spring Boot框架的网上蛋糕销售系统

随着互联网的普及和电子商务的迅猛发展,网上购物已经成为人们日常生活的一部分。蛋糕作为一种受欢迎的食品,其销售市场也逐渐向网络化方向发展。网上蛋糕销售系统能够打破时间和地域的限制,让消费者随时随地浏览和购买蛋糕,同时也为蛋糕商家提供了一个展示和销售产品的平台。该系统的开发旨在提高蛋糕预定和销售的便捷性,节约时间和经济成本,并推动蛋糕市场的进一步发展。开发语言:Java,一种面向对象的编程语言,具有跨平台性、稳定性和安全性等特点,适用于构建大型、复杂的Web应用程序。 框架:Spring Boot,一个基于Sp

2301_81127431的博客 999

初入Spring--AOP底层原理(代码)

什么是 AOP (1)面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得 业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 (2)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能 AOP术语 1、连接点 (可增强的方法) 2、切入点(可增强方法中我们选中的增强的方法) 3、通知(增强) 就是增强方法的术语 4、切面(是一个动作,即把通知/增强应用到切入点的过程) 理解AOP 我的理解就是在完成基础功能后,我们把完成基础功能的类代理了,意思就是被代

luerdao_的博客 269

基于MySQL的京东用户行为分析

对京东用户行为的分析,利用AARRR模型进行分析。

SelenaSelena的博客 1916

【mybatis源码解析】(三)MapperRegistry类解析

前面两篇文章介绍了大体流程,这篇着重介绍跟MapperRegistry相关的类,MapperRegistry是什么? MapperRegistry翻译过来就是映射器注册表 看看他的属性 config是存储了mybatis相关配置的类 knownMappers是一个以mpper接口类对象为key,MapperProxyFactory为值的map集合

爱音乐的程序猿的博客 1497

OpenBCI脑电帽硬件DIY与低成本搭建实战

本文详细介绍了如何通过第三方兼容硬件和开源设计,低成本DIY一套功能完备的OpenBCI脑电采集系统。从硬件选购、组装、软件配置到信号调试,提供了完整的实战指南,将总成本控制在千元级别,使脑机接口技术对爱好者、学生和研究者变得更加触手可及。

weixin_29322855的博客 809

【已解决】如何在服务器中下载huggingface模型,解决huggingface无法连接

在服务器上使用huggingface模型时,如果直接指定模型名称,用AutoTokenizer.from_pretrained(“model_name”),可能会由于网络原因会报错 Failed to connect to huggingface.co port 443 after 75018 ms: Operation time out因此我们需要下载模型到服务器上,得到模型本地的路径model_dir,再通过AutoTokenizer.from_pretrained(model_dir)方式来使用。

a61022706的博客 4万+

数据库之Mybatis的Mapper实现原理

前言 在日常开发中,本文详细阐述,。 举例说明: 假设线程A需要执行一个事务X,事务X中包含两次具体的数据库操作Y+Z。 线程A在执行第一个数据库操作Y时,新建了一个SqlSession,然后在执行第二次数据库操作Z时,因为当前的事务还没有执行结束,不用新建SqlSession,这个时候我们的SqlSessionHolder就派上用场了。他的具体作用是在第一次数据库操作Y结束后,生成一个SqlSessionHolder,并将执行Y操作的SqlSession与其绑定,然后在第二次数据库操作Z时,通过SqlSe

齐祖的博客 4592

V-REP(Cooprliesim EDU)自学笔记 实现UR5机械臂末端按轨迹移动

V-REP(Cooprliesim EDU)自学笔记 实现UR5机械臂末端按轨迹移动

xu_white的博客 7586

Mybatis源码解析(八):Mapper代理原理

文章主要围绕着如下几个点,展开源码解析:是如何进行解析的?是如何生成的代理对象?是怎么完成的增删改查操作?标签配置的包名下的Mapper接口文件都会被加载成对应的代理类工厂通过Mapper接口获取同包同名的xml文件,并解析Mapper接口通过jdk代理创建代理类,接口方法匹配xml中标签的id值,执行增删改查。

从基础到源码解析的学习记录 3127

innovus获取mem pin shape box脚本

innovus mem 的pin shae只能通过attitude editor看属性获取其pin shape的box,但是想用脚本处理一定box时,没有别的办法能直接获取box属性。我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 1118

Python开发MCP Client

全部例子只是MCP Client访问MCP Server的过程,那么这样其实就失去了MCP协议的创建的初衷,和大模型集成后才能发挥MCP最大的作用。

Criss@陈磊 2980

mybatis原理 及 mybaits-plus是怎样将BaseMapper注入到接口中

本文档主要描述mybaits-plus是怎样将BaseMapper注入到接口中,并且能够运行的。要了解这个就要了解mybatis是怎样运行的。mybatis通过三个步骤运行。第一扫描配置文件及xml将配置信息和xml中的每个方法登记再config中。第二执行时通过代理执行登记的方法信息。第三执行过程解析配置及参数等信息。 mybatis 扫描xml并登记 Mybatis Co...

binghao1987000的博客 9135

高级数据结构之R树(R-tree)

R树(R-tree)是一种将B树扩展到多维情况下得到的数据结构,它最初由Antonin Guttman于1984年提出。B树的结点中会存储一个键的集合,这些键把线分成片段,沿着那条线的点仅属于一个片段。因此,B树使得我们可以很容易地找到点。如果把沿线各处的点表示成B树结点,我们就能够确定点所属唯一子结点,在那里可以找到该点。 Antonin Guttman在他提出R树的经典论文中给出的R树例子...

白马负金羁 1万+

Mybatis中Mapper动态代理的实现原理

一、概述我们知道,Mybatis实现增删改查需要进行XML的配置,其基本的配置如下:<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

想作会飞的鱼的博客 3万+

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Mybatis源码中Mapper的动态代理实现原理

Mybatis源码中Mapper的动态代理实现原理现在工作中用的最多的就是Mybatis这款半自动ORM框架,用的久却对其了解不是很深,现在准备对其进行一些深入的学习,顺便对知识进行查漏补缺.本篇是对Mapper动态代理原理的详解.代理模式定义为另一个对象提供一个替身或者占位符以控制对这个对象的访问.也就是说目的是控制对象行驶他的职责.当然也可以增强其职责,比如Spring AOP.

laixiangshun的博客 3019

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

MyBatis之Mapper的动态代理实现原理

为了方便理解MyBatis的Mapper的动态代理实现原理,下面编写简单的动态代理实现方式,模仿MyBatis的Mapper实现一个UserMapper,通过定义Mapper接口UserMapper,然后调用 UserMapper userMapper = MapperFactory.getMapper(UserMapper.class); List<Integer> list = userMapper.getList(); 获取UserMapper的代理对象,代理对象直接返回一个Li.

alterhz的博客 728

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

MyBatis的Mapper接口动态代理原理

MyBatis的Mapper接口动态代理原理1、什么是mapper接口的动态代理创建sqlsession对象不使用动态代理使用动态接口代理2、mapper接口动态代理的代码实现2.1假定一个接口2.2使用java的动态代理方式,创建一个类2.3测试代码 1、什么是mapper接口的动态代理 创建sqlsession对象 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new S

java_xiaoba1的博客 504

MyBatis 源码解析:Mapper 接口动态代理原理

MyBatis 通过动态代理为 Mapper 接口生成实现类,开发者无需手动编写实现类,SQL 语句会在运行时自动执行。本文深入解析 MyBatis 中的动态代理机制,讲解 `MapperProxy` 如何拦截接口方法调用并执行 SQL。通过自定义实现,我们将模拟 MyBatis 的代理机制,帮助开发者更好地理解其工作原理。

捕风捉你 · 星桥API接入与大模型实战 1142

mybatis的Mapper代理原理

前言:在mybatis的使用中,我们会习惯采用XXMapper.java+XXMapper.xml(两个文件的名字必须保持一致)的模式来开发dao层,那么问题来了,在XXMapper的文件里只有接口,里面只有方法体,在XXMapper.xml的文件里,里面只有sql,而在java中,方法调用必须通过对象,除非是静态方法,但是一般的接口里面的方法都不是静态的,那么mybatis的对象在哪里?是如何产...

黑马程序员广州中心的专栏 224

《MyBatis动态代理实现Mapper接口原理》

MyBatis通过动态代理实现Mapper接口的无实现类调用。核心流程为:1)初始化时,MyBatis为每个Mapper接口创建MapperProxyFactory代理工厂;2)调用getMapper()时,工厂生成包含SqlSession的代理对象;3)方法调用被MapperProxy拦截,通过接口名+方法名定位SQL语句;4)由MapperMethod执行具体SQL操作,通过Executor执行并返回结果。整个过程利用JDK动态代理和配置映射,实现了接口方法与SQL语句的自动绑定,开发者只需定义接口即可

m0_74162426的博客 484

本文将通过模拟Mybatis动态代理生成Mapper代理类,讲解Mybatis原理

本文将通过模拟Mybatis动态代理生成Mapper代理类,讲解Mybatis原理 1.平常我们是如何使用Mapper的 先写一个简单的UserMapper,它包含一个全表查询的方法,代码如下 public interface UserMapper { @Select("select * from user") public List<User> queryAll(); } 然后大家思考一个问题,我们平时是怎么使用这个UserMapper的? 很多时候我们会把Mybatis和Spring整合起

qq_33349365的博客 449

mybatis入门-mapper代理原理

原始dao层开发     在我们用mybatis开发了第一个小程序后,相信大家对于dao层的开发其实已经有了一个大概的思路了。其他的配置不用变,将原来的test方法,该为dao的方法,将原来的返回值,直接在dao层进行一下接收就可以了。依然是老一套,先是大框架,然后写配置文件及UserMapper.xml文件这一系列的操作。如果不明白的,请参考本人博客《入门第一个程序》。     我们需要做的

birthmarkqiqi的专栏 438

Mybatis Mapper接口动态代理实现原理

摘自《Mybatis从入门到精通》(刘增辉) 通过上面的学习,大家可能会有一个疑问,为什么 Mapper 接口没有实现类却能被正常调用呢? 这是因为 MyBaits 在 Mapper 接口上使用了动态代理的一种非常规的用法,熟悉这种动态代理的用法不仅有利于理解 MyBatis 接口和 XML 的关系,还能开阔思路 。 接下来提取出这种动态代理的主要思路,用代码来为大家说明。 假设有一个如下的 Ma...

一枝会思想的芦苇的博客 3482

mybatis-mapper的动态代理原理

一、配置mapper 在进行动态代理前,我们需要在mybatis的全局配置环境中配置mapper标签,告诉mybatis我的mapper都在哪,同时需要在项目中创建mapper的xml文件和对应的接口 注意:mapper的xml文件要与接口名一样,namespace也需要设置为接口的全路径名,只有这样才能在为mapper接口做动态代理的时候找到正确的sql语句 二、源码分析 涉及到的模块 1. DefaultSqlSession:sqlsession的实现类,对jdbc的connection进行了封装 2.

qq_42861526的博客 1365

MyBatis Mapper 实现原理彻底解密——从动态代理到 JDBC 执行全链路剖析

MyBatis 用 JDK 动态代理为 Mapper 接口生成内存中的代理实例($ProxyXX),代理类继承自 Proxy,实现目标 Mapper 接口。代理类中,super.h 就是 MyBatis 的 MapperProxy 实例,所有 Mapper 方法调用都会转发到 MapperProxy.invoke。invoke 方法通过“接口全类名 + 方法名”定位 XML 中的 SQL 元数据,再执行 JDBC 操作。

Java架构师之路的博客 374
上一篇: MyBatis总体流程
下一篇: MyBatis延迟加载原理(源码剖析)
躺平程序猿
博客等级 码龄8年 4870粉丝 71原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

躺平程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址