Mybatis

SqlSessionFactoryBuilder-->build()方法

-->SqlSessionFactory-->openSession()方法

-->SqlSession(DeafaltSqlSession)-->用内部Configuration对象的mapperRegistry的getMapper()方法

-->getMapper()方法,会先从缓存(knownMappers)中查找 MapperProxyFactory 对象,如果没有找到,则创建一个新的 MapperProxyFactory 对象,并缓存起来。然后使用 MapperProxyFactory.newInstance() 方法

-->new mapperProxy(implements InvocationHandler)

-->把MapperProxy传入 Proxy.newProxyInstance()

-->获得Mapper代理对象 该对象重写的Invoke方法,生成内部接口MapperMethodInvoker的实现类的invoke方法

-->mapperMethod的execute(SqlSession,args)

20:28:39-1689251319091.png

开始真正的执行sql

-->查找代理对象的MapperProxy中的methodCache中缓存的MapperMethodInvoker(MapperProxy的内部接口)对象(根据方法名和参数名),如果找到了对应的 MapperMethodInvoker对象,则使用该对象来执行 SQL 语句。如果没有找到对应的 MapperMethodInvoker 对象,则根据方法名和参数类型来构造一个新的 MapperMethodInvoker 对象,并保存在 MethodCache中供下次使用。

MapperMethodInvoker 对象封装了 MapperMethod 对象和 SqlSession 对象,用于执行 SQL 语句。

SqlSessionFactoryBuilder 先是通过传入的扫描配置文件的输入流,解析生成Configuration对象

16:27:50-1689236869330.png

然后调用build()方法生成DefaultSqlSessionFactory对象

16:26:17-1689236776591.png

DefaultSqlSessionFactory调用openSession()方法生成DefaultSqlSession,形参有Executor,Configuration,是否开启事务

16:33:07-1689237186860.png

defaultSqlSession在执行sql的时候是利用,该对象里封装的Executor对象执行sql

16:38:37-1689237517008.png

DefaultSqlSession 在调用executor的时候,是采用如下顺序的(不是一定的)

CacheExecutor(二级缓存执行器) --> BaseExecutor(一级缓存执行器) --> SimpleExecutor(最简单执行器)

SimpleExecutor根据Configuration生成相应StatementHandler(Statement、Prepared、Callable)

17:09:58-1689239397507.png

Last updated