mybatis源码专题(二)【SqlSession对象】

本文深入探讨mybatis中的SqlSession对象,解析其作为数据库会话接口的角色,详细阐述SqlSession的创建过程,包括DefaultSqlSession的内部结构和如何通过configuration对象管理MappedStatement。同时,对比分析了两种SqlSession的应用方式,方式一是直接使用namespace+id,方式二是通过getMapper创建代理对象,揭示了方式二的封装性和便利性,尽管在性能上略逊于方式一。
摘要由CSDN通过智能技术生成

mybatis源码专题(二)

1)什么是SqlSession

SqlSession是实现与数据库进行会话的入口对象

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("classpath:mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
2)SqlSession对象应用过程分析

在这里插入图片描述
1、由于我们通过上面拿到的SqlSessionFactory的实例对象是DefaultSqlSessionFactory,所以我们通过该factory创建出来的SqlSession实例对象是DefaultSqlSession

public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

2、通过DefaultSqlSession我们知道其里面包含一个configuration对象,configuration对象以Map集合的方式存储了所有MappedStatement对象,通过namespace+id就可以命中相应的MappedStatement对象,然后交由executor去处理

try {
	  //statement位命名空间namespace+id
      MappedStatement ms = configuration.getMappedStatement(statement);
      //命中namespace+id对应的MappedStatement 对象,交由executor去处理
      //对于程序创建什么类型的executor,可配置
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }

3、在Executor中利用MappedStatement的实例对象获取对应的Configuration,在通过Configuration创建对应的StatementHandler对象

 Configuration configuration = ms.getConfiguration();
 StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);

4、在StatementHandler中分别对入参的处理和结果集的映射

parameterHandler.setParameters(statement);
resultSetHandler.<E> handleResultSets(statement);
3)SqlSession应用方式

方式一:通过命名空间namespace+id直接命中MappedStatement对象
方式二:通过sqlSession的getMapper(Class type)函数创建一个代理对象(这种方式实际开发中用的多)

分析

方式一所命中MappedStatement对象的key是通过mapper.xml文件中的namespace+id获得,而方法二是通过接口的包名+方法名去命中对应的MappedStatement对象,通过getMapper函数生成一个代理类,我们通过调用该代理类的方式就可以做出对用的操作,可以说方式二是在方式一的基础上做了一下底层封装,方便我们日常开发,但是性能上来看,方式一毫无争议是要比方式二高

附图:如何获取代理对象

在这里插入图片描述

附图:代理对象如何执行

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值