MyBatis源码之菜鸟理解的流程

执行流程

获取配置文件的输入流

InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

获取配置文件的输入流的流程是:

1.Rescources 调用getResources(String resources)加载配置文件

2.调用getResourceAsStream(ClassLoader loader, String resource)方法

3.通过classLoaderWrapper.getResourceAsStream(resource, loader)方法来获取流

4最后通过对该数组进行判断,看类加载器中所读的流是否为null,如果不为null,则返回InputStream对象

通过SqlSessionFactoryBuilder获取SqlSessionFactory

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

build()方法

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //通过输入流构建XMLConfigBuilder对象
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

获取SqlSessionFactory的流程是:
1.通过SqlSessionFactoryBuilder.build(InputStream inputStream, String environment, Properties properties)构建
2.通过输入流创建XMLConfigBuilder对象,并使用XMLConfigBuilder.parse()方法将输入流转换为Configuration对象
3.利用Configuration对象创建DefaultSqlSessionFactory对象

通过SqlSessionFactory获取SqlSession

SqlSession session = factory.openSession();

通过SqlSessionFactory获取SqlSession的流程是:
1.通过configuration对象获取Environment对象,包括environment id,DataSource , 事物工厂
2.通过事务工厂获取事务
3.创建执行器Executor
4.创建DefaultSqlSession对象。

获取Mapper

UserMapper mapper=session.getMapper(UserMapper.class);

获取Mapper的流程是:

1.调用efauitDsqlsession中getMapper方法

2.接着调用configuration的getMapper(Class<T> type,Sqlsession sqlSession)方法

3.再调用MapperRegistry中的getMapper(Class<T> type,Sqlsession sqlSession)方法

4.接着通过MapperProxyFactory 工厂对象来获取 MapperProxy 在里面使用反射和动态代理的方式来获取最终的mapper对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值