mybatis的简单执行流程-面试用

1、Configuration

XMLConfigBuilder调用parse()方法解析Mybatis配置文件,生成Configuration对象

XMLConfigBuilder parser > Configuration

SqlSessionFactory = new DefaultSqlSessionFactory ( config );

session = factory.openSession();

sqlSession.getMapper(UserMapper.class);

通过Session来得到UserMapper.java类的代理对象。

每一个Mapper文件都有一个对应的MapperProxyFactory,为什么需要MapperProxyFactory

2、因为MapperProxyFactory可以用来生成代理对象。

MapperProxyFactory是如何产生代理对象: 内部通过目标类转成MapperProxy,在通过Proxy生成代理对象。

MapperProxy实现了InvocationHandler接口,所以MapperProxy具有拦截功能,

Proxy如何产生对象的

Proxy.newProxyInstance(getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);

注意第一个参数是类加载器,第二个是代理要实现的接口,第三个参数是InvocationHandler的实例对象。

Proxy把MapperProxy当做InvocationHandler,Mapper当做接口来生成代理类。最终代理类会实现UserMapper接口,并且被调用时,会被InvocationHandler拦截也就是被MapperProxy拦截。

当调用方法,会被MapperProxy的invoke方法拦截,invoke会做下面操作

通过方法名Method查询得到MapperMethodInvoker对象,MapperMethodInvoker是做什么

3、MapperMethod

MapperMethod主要包含下面2个东西

java 复制代码
private final MapperMethod.SqlCommand command;
private final MapperMethod.MethodSignature method;

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new MapperMethod.SqlCommand(config, mapperInterface, method);
    this.method = new MapperMethod.MethodSignature(config, mapperInterface, method);
}

SqlCommand和MethodSignature干嘛用的。

1、SqlCommand一个内部类 封装了SQL标签的类型insert update delete select

2、MethodSignature一个内部类 封装了方法的参数信息 返回类型信息等

MapperMethod有个execute,就是开始执行sql的操作.在execute里面,通过类型找到事insert还是update,在通过返回值类型找具体方法,处理类型

在通过类+方法名当做ID去Mapper.xml里面找对应的sql执行语句。

关于MapperMethod可以看这个文章:《MapperMethod》

相关推荐
躲在云朵里`3 小时前
Spring Scheduler定时任务实战:从零掌握任务调度
java·数据库·mybatis
Java小白程序员1 天前
MyBatis基础到高级实践:全方位指南(中)
数据库·mybatis
山楂树下懒猴子1 天前
ChatAI项目-ChatGPT-SDK组件工程
人工智能·chatgpt·junit·https·log4j·intellij-idea·mybatis
Mr_hwt_1231 天前
基于mybatis-plus动态数据源实现mysql集群读写分离和从库负载均衡教程(详细案例)
数据库·spring boot·mysql·mybatis·mysql集群
Z_z在努力2 天前
【杂类】Spring 自动装配原理
java·spring·mybatis
little_xianzhong2 天前
关于对逾期提醒的定时任务~改进完善
java·数据库·spring boot·spring·mybatis
MadPrinter2 天前
SpringBoot学习日记 Day11:博客系统核心功能深度开发
java·spring boot·后端·学习·spring·mybatis
奔跑吧邓邓子2 天前
【Java实战㉟】Spring Boot与MyBatis:数据库交互的进阶之旅
java·spring boot·实战·mybatis·数据库交互
lunzi_fly2 天前
【源码解读之 Mybatis】【基础篇】-- 第1篇:MyBatis 整体架构设计
java·mybatis
摸鱼仙人~2 天前
深入理解 MyBatis-Plus 的 `BaseMapper`
java·开发语言·mybatis