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》

相关推荐
DokiDoki之父13 小时前
MyBatis—增删查改操作
java·spring boot·mybatis
DokiDoki之父20 小时前
Mybatis—入门 & (配置)SQL提示和日志输出
数据库·sql·mybatis
计算机学姐3 天前
基于微信小程序的垃圾分类管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
哲此一生9843 天前
SpringBoot3集成Mybatis(开启第一个集成Mybatis的后端接口)
java·spring boot·mybatis
九转苍翎3 天前
Java外功精要(3)——Spring配置文件和mybatis
spring boot·mybatis
程序员三明治3 天前
【Mybatis从入门到入土】ResultMap映射、多表查询与缓存机制全解析
java·sql·缓存·mybatis·resultmap·缓存机制·多表查询
此剑之势丶愈斩愈烈3 天前
mybatis-plus分页插件使用
mybatis
!if4 天前
springboot mybatisplus 配置SQL日志,但是没有日志输出
spring boot·sql·mybatis
讓丄帝愛伱4 天前
Mybatis Log Free插件使用
java·开发语言·mybatis
gaoshan123456789104 天前
‌MyBatis-Plus 的 LambdaQueryWrapper 可以实现 OR 条件查询‌
java·tomcat·mybatis