mybatis源码学习

**一、mybatis是的配置加载原理
1 MapperRegistry
xmybatis的xml或者注解加载的时候,解析xml或者注解,通过MapperRegistry注册一个个mapper
在这里插入图片描述
在这里插入图片描述
knownMappers是一个Map<Class<?>, MapperProxyFactory<?>> 对象,通过addMapper实现注册mapper,创建一个定义的接口与对应的工厂
1 MapperProxyFactory
通过代理工厂创建MapperProxy
在这里插入图片描述
使用了这个代理工厂创建MapperProxy大大降低了程序的耦合度
1.3 MapperProxy
在这里插入图片描述
使用java常用的设计模式动态代理,Map<Method, MapperMethod> methodCache将mapper接口定义的Method和通过xml配置的select、update等方法对应并存到内存当中,执行update、select等操作通过动态代理SqlSession执行对应的方法。
4 Configurate
mybatis的configuration使用的是设计模式中修饰者模式,作用是一个桥梁,将mybatis个各个组件联系起来,同时也是一个mybatis的全局配置。

二、sql的执行
1、通过SqlSessionFactory创建SqlSession
Mybatis的核心是SqlSession,SqlSession将java基本的数据库相关操作进行了封装,通过SqlSessionFactory可以构建不同需求的SqlSession

public interface SqlSessionFactory {

  SqlSession openSession();//默认
  SqlSession openSession(boolean autoCommit);//可以设置是否自动提交事务
  SqlSession openSession(Connection connection);//通过jdk的Connection对象创建
  SqlSession openSession(TransactionIsolationLevel level);//设置事务的隔离级别
  SqlSession openSession(ExecutorType execType);//sql执行类型 有三种 SIMPLE, REUSE, BATCH
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);
  Configuration getConfiguration();
}

1.1、执行器类型(ExecutorType )
SIMPLE:只为每个语句创建一个PreparedStatement,执行完sql销毁PreparedStatement
REUSE:重复使用PreparedStatements,执行完不销毁
BATCH:批量处理,重复使用同一个PreparedStatements,执行完不销毁
1.2、事务隔离级别(TransactionIsolationLevel)
NONE:不设置事务隔离级别
READ_COMMITTED:读已提交
READ_UNCOMMITTED:读未提交
REPEATABLE_READ:可重复读
SERIALIZABLE:串行化,事务最高隔离级别

2、SqlSession调用insert,select等方法执行sql
以selectList为例子:
在这里插入图片描述
2.1 MappedStatement
首先通过Configuration拿到对应的MappedStatement,他是动态sql的关键,是对sql的封装在这里插入图片描述
statement就是对应的update、select这些方法配置的id属性。通过Configura获取到内存中对应的MappedStatement 对象,然后通过执行器去执行sql。
2.2 Executor
执行器Executor是mybatis调度的核心,负责SQL语句的生成和查询缓存的维护。
在这里插入图片描述
在执行器的Query方法中将参数绑定到MappedStatement对象当中,然后创建一个缓存对象,上面说到执行器的类型有三种,我们需要根据日常需要选择合适执行器
在这里插入图片描述
这个重载的query才是最终执行sql的方法,首先根据缓存的key判断是否存在本地缓存当中,没有缓存则从数据库查询

猜你喜欢

转载自blog.csdn.net/qq_36027670/article/details/84792246