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》

相关推荐
8***f39535 分钟前
Spring 中使用Mybatis,超详细
spring·tomcat·mybatis
w***76551 小时前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
张较瘦_14 小时前
SpringBoot3 | MyBatis-Plus 搞定宠物管理:从0到1实现增删改查
mybatis·宠物
沙白猿21 小时前
Redis报错:A bean with that name has already been defined in class path resource
spring boot·redis·mybatis
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
柒.梧.2 天前
SSM常见核心面试问题深度解析
java·spring·面试·职场和发展·mybatis
rabbit_pro2 天前
Java使用Mybatis-Plus封装动态数据源工具类
java·python·mybatis
IT_Octopus2 天前
java 实体属性 Map 解决 mybatis-plus wrapper selectone 查mysql json类型为null 问题
java·mysql·mybatis
Dolphin_Home2 天前
MyBatis 核心属性详解笔记(由浅入深)
笔记·mybatis