mybatis执行流程

//通过配置文件取到sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过sqlSessionFactory取到sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过sqlSession取到对应的mapper
userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.getUser(1);

具体执行流程

sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
点进去build
image
继续往里点(核心就是这个this.build)
image

  • 其中parser.parse()是解析配置文件,点进去
    image
  • 继续点击parseConfiguration(依次解析每个标签)
    image
  • 其中最后的mappers是解析这玩意,同时把所有的mapper添加到MapperRegistry里
    image
    image
    image

继续点击build
(最后返回SqlSessionFactory的实现类DefaultSqlSessionFactory,用于取到SqlSession)
image
SqlSession sqlSession = sqlSessionFactory.openSession();
点击openSession,选择DefaultSqlSessionFactory
image

  • 自动提交默认为false
    image

点击openSessionFromDataSource
image

  • environment是取得刚解析xml得到的配置参数
  • tx是创建一个新事务,用于提交回滚操作
  • executor是一个执行器,是个接口(一般用SimpleExecutor来执行,实现类),他是mybatis的核心执行器,相当于jdbc中的statement,发送sql语句并执行。
  • 返回DefaultSqlSession,携带着this.configuration, executor, autoCommit

userMapper = sqlSession.getMapper(UserMapper.class);
点击getMapper,选择DefaultSqlSession
image
image
image
再次点击getMapper
image
点击newInstance
image
image
userMapper.getUser(1);

  • 代理对象的getUser方法执行其实走的是MapperProxy的invoke方法
    image
  • 点击execute方法
    image
  • 点击executeWithResultHandler
    image
    image
  • 判断是否有缓存,先从二级缓存中获取,如二级缓存中没有数据,走delegate(BaseExecutor)的query方法 ,也就是一级缓存localCache,如果一级缓存没有数据,则走queryFromDatabase方法查数据库,从数据库查到数据,放入到一级缓存中
    image
    image
    image

总结

mybatis运行时要先通过resources把核心配置文件也就是mybatis.xml文件加载进来,然后通过xmlConfigBulider来解析,解析完成后把结果放入configuration中,并把它作为参数传入到build()方法中,并返回一个defaultSQLSessionFactory。我们再调用openSession()方法,来获取SqlSession,在构建SqlSession的同时还需要transaction和executor用于后续执行操作。
image

参考博客:
https://blog.csdn.net/qq_38270106/article/details/93398694

原文地址:https://www.cnblogs.com/kaka-qiqi/p/14607047.html