debug数据源之sqlSessionFactory

本文详细介绍了在MyBatis中,如何通过SqlSessionFactoryBean配置数据源,以及在处理持久层请求时,SqlSession的创建与管理。通过debug,揭示了从SqlSessionFactory到SqlSession,再到MapperFactoryBean的创建过程。分析了SqlSessionTemplate和SqlSessionManager在事务管理和线程安全性中的角色,解释了MyBatis如何在Spring环境下利用TransactionSynchronizationManager进行资源管理。
摘要由CSDN通过智能技术生成

使用mybatis的时候会配置sqlSessionFactoryBean,将数据源传入。我对于mybatis的理解是当 处理持久层的请求时,ThreadLocal 内会持有一个数据源的jdbc 链接。这样 该线程的所有数据操作都是用一个链接来操作。完后关闭链接。debug的目的是看下到底是怎么做的。

SqlSessionFactoryBean内有很多对象,debug下来发现最关键是configuration对象。他持有用户配置的datasource。在afterPropertiesSet()方法中打上断点。

  public void afterPropertiesSet() throws Exception {
    notNull(dataSource, "Property 'dataSource' is required");
    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
              "Property 'configuration' and 'configLocation' can not specified with together");

    this.sqlSessionFactory = buildSqlSessionFactory();
  }

启动程序 进入断点

这个方法调用过程是spring创建bean的过程。

进入buildsqlSessionFactory(),很长,主要内容是通过配置来初始化configuration。然后通过configuration来创建一个sqlSessionFactory。

  protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;
//删除配置代码

    if (this.transactionFactory == null) {
      this.transactionFactory = new SpringManagedTransactionFactory();
    }
//删除配置代码
    configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));

 //删除配置代码

    return this.sqlSessionFactoryBuilder.build(configuration);
  }

最后sqlSessionFactoryBuilder.build new了一个DefaultSqlSessionFactory。顾名思义他的作用就是sqlSession的创建工厂

创建的sqlSession内持有Environment对象,内含我们配置的datasource 和TransactionFactory

 private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值