mybatis学习笔记(三)(mybatis的源码解析)

本文详细介绍了MyBatis的架构设计,包括API接口层、数据处理层和基础支撑层,重点解析了初始化过程、执行SQL流程、Executor和StatementHandler的源码。此外,还探讨了Mapper接口的代理方式、二级缓存的开启流程和工作原理,以及延迟加载的概念和实现原理。最后,总结了MyBatis中运用的设计模式,如Builder、工厂和代理模式。
摘要由CSDN通过智能技术生成

模块一任务三笔记

1.myabtis 架构设计

架构设计:

在这里插入图片描述

(1) API接⼝层:提供给外部使⽤的接⼝ API,开发⼈员通过这些本地API来操纵数据库。接⼝层⼀接收
到调⽤请求就会调⽤数据处理层来完成具体的数据处理。
MyBatis和数据库的交互有两种⽅式:
a. 使⽤传统的MyBati s提供的API ;
b. 使⽤Mapper代理的⽅式
(2) 数据处理层:负责具体的SQL查找、SQL解析、SQL执⾏和执⾏结果映射处理等。它主要的⽬的是根
据调⽤的请求完成⼀次数据库操作。
(3) 基础⽀撑层:负责最基础的功能⽀撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是
共 ⽤的东⻄,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的⽀撑

主要构件:

在这里插入图片描述

总体流程:

(1) 加载配置并初始化
触发条件:加载配置⽂件
配置来源于两个地⽅,⼀个是配置⽂件(主配置⽂件conf.xml,mapper⽂件*.xml),—个是java代码中的注解,将主配置⽂件内容解析封装到Configuration,将sql的配置信息加载成为⼀个mappedstatement对象,存储在内存之中

(2) 接收调⽤请求
触发条件:调⽤Mybatis提供的API
传⼊参数:为SQL的ID和传⼊参数对象
处理过程:将请求传递给下层的请求处理层进⾏处理。

(3) 处理操作请求
触发条件:API接⼝层传递请求过来
传⼊参数:为SQL的ID和传⼊参数对象
处理过程:
(A) 根据SQL的ID查找对应的MappedStatement对象。
(B) 根据传⼊参数对象解析MappedStatement对象,得到最终要执⾏的SQL和执⾏传⼊参数。
© 获取数据库连接,根据得到的最终SQL语句和执⾏传⼊参数到数据库执⾏,并得到执⾏结果。
(D) 根据MappedStatement对象中的结果映射配置对得到的执⾏结果进⾏转换处理,并得到最终的处理结果。
(E) 释放连接资源。
(4) 返回处理结果
将最终的处理结果返回。


2-5.源码分析

初始化过程:

// 1.我们最初调⽤的build
public SqlSessionFactory build (InputStream inputStream){
   
    //调⽤了重载⽅法
    return build(inputStream, null, null);
}
// 2.调⽤的重载⽅法
public SqlSessionFactory build (InputStream inputStream, String environment,
											Properties properties){
   
    try {
   
        // XMLConfigBuilder是专⻔解析mybatis的配置⽂件的类
        XMLConfigBuilder parser = new XMLConfigBuilder
        								(inputstream,environment, properties);
        //这⾥⼜调⽤了⼀个重载⽅法 parser.parse()的返回值是Configuration对象
        return build(parser.parse());
    } catch (Exception e) {
   
   		 throw ExceptionFactory.wrapException("Error building   SqlSession.", e)
	}
}

​ MyBatis在初始化时,将配置信息加载到org.apache.ibatis.session.Configuration 实例来维护
​ 配置⽂件解析部分:
​ Configuration对象 :(Configuration对象的结构和xml配置⽂件的对象⼏乎相同。)

/**
* 解析 XML 成 Configuration 对象。
*/
public Configuration parse () {
   
    //若已解析,抛出BuilderException异常
    if (parsed) {
   
        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    //标记已解析
    parsed = true;
    // 解析 XML configuration 节点
    parseConfiguration(parser.evalNode("/configuration"));
	return configuration;
}
/**
*解析XML
*/
private void parseConfiguration (XNode root){
   
        try {
   
            //issue #117 read properties first
            // 解析 <properties /> 标签
            propertiesElement(root.evalNode("properties"));
            // 解析〈settings /> 标签
            Properties settings =
            settingsAsProperties(root.evalNode("settings"));
            //加载⾃定义的VFS实现类
            loadCustomVfs(settings);
            // 解析 <typeAliases /> 标签
            typeAliasesElement(root.evalNode("typeAliases"));
            //解析<plugins />标签
            pluginElement(root.evalNode("plugins"));
            // 解析 <objectFactory /> 标签
            objectFactoryElement(root.evalNode("objectFactory"));
            // 解析 <objectWrapperFactory /> 标签
            objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
            // 解析 <reflectorFactory /> 标签
            reflectorFactoryElement(root.evalNode("reflectorFactory"));
            // 赋值 <settings /> ⾄ Configuration 属性
            settingsElement(settings);
            // read it after objectFactory and objectWrapperFactory issue
            #631
            // 解析〈environments /> 标签
            environmentsElement(root.evalNode("environments"));
            // 解析 <databaseIdProvider /> 标签
            databaseldProviderElement(root.evalNode("databaseldProvider"));
            // 解析 <typeHandlers /> 标签
            typeHandlerElement(root.evalNode("typeHandlers"));
            //解析<mappers />标签
            mapperElement(root.evalNode("mappers"));
        } catch (Exception e) {
   
        	throw new BuilderException
                    ("Error parsing SQL Mapper Configuration.Cause:" e, e);
        }
}

MappedStatement :
作⽤:MappedStatement与Mapper配置⽂件中的⼀个select/update/insert/delete节点相对应。mapper中配置的标签都被封装到了此对象中,主要⽤途是描述⼀条SQL语句。

​ 初始化过程:加载配置⽂件的过程中,会对mybatis-config.xm l中的各个标签都进⾏解析,其中有mappers 标签⽤来引⼊mapper.xml⽂件或者配置mapper接⼝的⽬录。

<select id="getUser" resultType="user" >
	select * from user where id=#{id}
</select>

​ select标签会在初始化配置⽂件时被解析封装成⼀个MappedStatement对象,然后存储在Configuration对象的mappedStatements属性中,mappedStatements 是⼀个HashMap,存储时key=全限定类名+⽅法名,value =对应的MappedStatement对象。

在configuration中对应的属性为

Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>
    													("Mapped Statements collection")

在 XMLConfigBuilder 中的处理

private void parseConfiguration(XNode root) {
   
    try {
   
        //省略其他标签的处理
        mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
   
    	throw new BuilderException("Error parsing SQL Mapper  Configuration.Cause:" + e, e);
    }
}

到此对xml配置⽂件的解析就结束了,回到步骤2.中调⽤的重载build⽅法

// 5.调⽤的重载⽅法
public SqlSessionFactory build(Configuration config) {
   
	//创建了 DefaultSqlSessionFactory 对象,传⼊ Configuration 对象。
	return new DefaultSqlSessionFactory(config);
}

执行sql流程:

sqlSession:

​ SqlSession是⼀个接⼝,它有两个实现类:DefaultSqlSession (默认) SqlSessionManager (弃⽤)
​ SqlSession是MyBatis中⽤于和数据库交互的顶层类,通常将它与ThreadLocal绑定,⼀个会话使⽤⼀个SqlSession,并且在使⽤完毕后需要close

​ 两个重要参数:

public class DefaultSqlSession implements SqlSession {
   
    private final Configuration configuration;
	private final Executor executor;
j

Executor:
Executor也是⼀个接⼝,他有三个常⽤的实现类:
BatchExecutor (重⽤语句并执⾏批量更新)
ReuseExecutor (重⽤预处理语句 prepared statements)
SimpleExecutor (普通的执⾏器,默认)

/6. 进⼊ openSession ⽅法。
public SqlSession openSession() {
   
	//getDefaultExecutorType()传递的是SimpleExecutor
	return   openSessionFromDataSource.
            		(configuration.getDefaultExecutorType(), null,false);
}
//7. 进⼊penSessionFromDataSource。
//ExecutorType 为Executor的类型,TransactionIsolationLevel为事务隔离级别,
//autoCommit是否开启事务
//openSession的多个重载⽅法可以指定获得的SeqSession的Executor类型和事务的处理
private SqlSession openSessionFromDataSource(ExecutorType execType,
						TransactionIsolationLevel level, boolean autoCommit) {
   
    Transaction tx = null;
    try{
   
        final Environment environment = configuration.getEnvironment();
        final TransactionFactory transactionFactory =
        getTransactionFactoryFromEnvironment(environment);
        tx = transactionFactory.newTransaction(environment.getDataSource(),
        level, autoCommit);
        //根据参数创建指定类型的Executor
        final Executor executor = configuration.newExecutor(tx, execType);
        //返回的是 DefaultSqlSession
        return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch(Exception e){
   
    	closeTransaction(tx); // may have fetched a connection so lets call  close()
    }

执⾏ sqlsession 中的 api

//8.进⼊selectList⽅法,多个重载⽅法。
 public <E > List < E > selectList(String statement) {
   
 	return this.selectList(statement, null);
 }
 public <E > List < E > selectList(String statement, Object parameter){
   
	 return this.selectList(statement, parameter, RowBounds.DEFAULT);
 }
 public <E > List < E > selectList(String statement, Object parameter, RowBounds rowBounds) {
   
     try {
   
         //根据传⼊的全限定名+⽅法名从映射的Map中取出MappedStatement对象
         MappedStatement ms = configuration.getMappedStatement(statement);
         //调⽤Executor中的⽅法处理
         //RowBounds是⽤来逻辑分⻚
         // wrapCollection(parameter)是⽤来装饰集合或者数组参数
         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();
 	}
}

executor源码:

​ executor.query()

//此⽅法在SimpleExecutor的⽗类BaseExecutor中实现
 public <E> List<E> query(MappedStatement ms, Object parameter, RowBound  rowBounds, 
                          					ResultHandler resultHandler) throws SQLException {
   
     //根据传⼊的参数动态获得SQL语句,最后返回⽤BoundSql对象表示
     BoundSql boundSql = ms.getBoundSql(parameter);
     //为本次查询创建缓存的Key
     CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
     return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
 }
 //进⼊query的重载⽅法中
 public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, 
               ResultHandler resultHandler, CacheKey key, BoundSql boundSql)  throws SQLException {
   
     ErrorContext.instance().resource(ms.getResource())
        					 .activity("executing a  query").object(ms.getId());
     if (closed) {
   
     	throw new ExecutorException("Executor was closed.");
     }
     if (queryStack == 0 && ms.isFlushCacheRequired()) {
   
     	clearLocalCache();
     }
     List<E> list;
     try {
   
         queryStack++;
         list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
         if (list != null) {
   
             handleLocallyCachedOutputParameters(ms, key, parameter,boundSql);
         } else {
   
             //如果缓存中没有本次查找的值,那么从数据库中查询
             list = queryFromDatabase(ms, parameter, rowBounds,
            resultHandler, key, boundSql);
         }
     } finally {
   
    	 queryStack--;
     }
     if (queryStack == 0) {
   
         for (DeferredLoad deferredLoad : deferredLoads) {
   
            deferredLoad.load();
         }
             // issue #601
    	 deferredLoads.clear();
         if (configuration.getLocalCacheScope() ==  LocalCacheScope.STATEMENT) {
   
             // issue #482 clearLocalCache();
         }
     }
     return list;
 }
 //从数据库查询
 private <E> List<E> queryFromDatabase(MappedStatement ms, Objectparameter, RowBounds rowBounds, 
            	 ResultHandler resultHandler, CacheKey key,BoundSql boundSql) throws SQLException {
   
     List<E> list;
     localCache.putObject(key, EXECUTION_PLACEHOLDER);
     try {
   
         //查询的⽅法
         list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
     } finally {
   
    	 localCache.removeObject(key);
     }
     //将查询结果放⼊缓存
     localCache.putObject(key, list);
     if (ms.getStatementType() == StatementType.CALLABLE) {
   
     	localOutputParameterCache.putObject(key, parameter);
     }
     return list;
 }
// SimpleExecutor中实现⽗类的doQuery抽象⽅法
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds
   				 rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException  {
   
     Statement stmt = null;
     try {
   
         Configuration configuration = ms.getConfiguration();
         //传⼊参数创建StatementHanlder对象来执⾏查询
         StatementHandler handler =  configuration.newStatementHandler
                            (wrapper, ms, parameter, rowBounds,resultHandler, boundSql);
         //创建jdbc中的statement对象
        stmt = prepareStatement(handler, ms.getStatementLog());
         // StatementHandler 进⾏处理
         return handler.query(stmt, resultHandler);
     } finally {
   
     	closeStatement(stmt);
     }
 }
 //创建Statement的⽅法
 private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
   
     Statement stmt;
     //条代码中的getConnection⽅法经过重重调⽤最后会调⽤openConnection⽅法,从连接池中获得连接。
     Connection connection = getConnection(statementLog);
     stmt = handler.prepare(connection, transaction.getTimeout());
     handler.parameterize(stmt);
     return stmt;
 }
 //从连接池获得连接的⽅法
 protected 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值