Mybatis源码分析系列之第二篇:Mybatis的数据存储对象

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: Mybatis源码分析系列之第二篇:Mybatis的数据存储对象

前言:SQLSession是对JDBC的封装

一:SQLSession和JDBC的对照说明

左边是我们的客户端程序,右边是我们的MySQL数据仓,或者叫MySQL实例

Mybatis是对JDBC的封装,将JDBC封装成了一个核心的SQLSession对象

JDBC当中的核心对象:Connection、Statement、ResultSet

二:三种Statement补充说明

Statement:普通的Statement

PeparedStatement:预编译Statement

CallableStatement:适用于存储过程Statement

三:Statement的作用

通过这些Statement与我们的数据库进行交互,然后由我们的结果集对象ResultSet对象进行封装。

SqlSession是对以上内容进行了封装。

相对于以上来讲,SQLSession是对JDBC的封装,SQLSessionFactory是创建SQLSession对象的工厂,我们还基于mybatis-config.xml配置Mybatis,并且在Mapper.xml当中配置SQL,了解到这里我们对于Mybatis的认知就比较权限

在Java中,或者说在JVM当中对Mybatis相关的配置信息进行封装。这里边设计到很多的配置文件,我们不可能说用点就读一次文件,这样会有极大的IO,IO是操作系统层面的资源,他的创建绝不是虚拟机单独完成的,是很耗时的,少操作或者能复用最好。 对于这种东西,我们都是在程序启动时一次性读取,存储在Java对象当中

MyBatis当中的配置信息一共有两种:mybatis-config.xml和DaoMapper.xml。

其中mybatis-config.xml封装成了org.apache.ibatis.session.Configuration对象,DAOMapper.xml封装成了MapperdStatement部分数据是在Configuration当中进行保存的。

基于以上认知,我们可以知道在Mybatis当中有两类对象:数据储存类对象 + 操作类对象。

第一章:Configuration对象

Configuration是数据存储类对象,是将Mybatis当中的mybatis-config.xml封装成Configuration对象,Mapper.xml封装成了MappedStatement对象,当然MappedStatement这样表述不是特别完整。

一:mybatis-config.xml与Configuration属性的映射关系

1:标签environments

mybatis-config.xml中的environments 标签:

<environments default="default">
        <environment id="default">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/suns?useSSL=false"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123456"></property>
            </dataSource>
        </environment>
    </environments>

Configuration当中的对应属性:

public class Configuration {
  protected Environment environment;
}

2:标签settings

mybatis-config.xml中的标签:

<settings>
      -- 应用二级缓存的一个内容。
         <setting name="cacheEnabled" value="true"/>
     </settings>

Configuration当中的:

protected boolean safeRowBoundsEnabled;
  protected boolean safeResultHandlerEnabled = true;
  protected boolean mapUnderscoreToCamelCase;
  -- 关联属性的懒加载配置
  protected boolean aggressiveLazyLoading;
  protected boolean multipleResultSetsEnabled = true;
  -- 主键生成的配置
  protected boolean useGeneratedKeys;
  protected boolean useColumnLabel = true;
  -- 应用二级缓存的一个内容
  protected boolean cacheEnabled = true;
  protected boolean callSettersOnNulls;
  protected boolean useActualParamName = true;
  protected boolean returnInstanceForEmptyRow;

cacheEnabled从这个属性我们可以看到,这个我们可以写也可以不写,因为我们不写的话我们默认走的就是默认值。

3:标签typeAliases

mybatis-config.xml中的s标签:

<typeAliases>
    <typeAlias type="com.baizhiedu.entity.User" alias="User"/>
    <typeAlias type="com.baizhiedu.entity.Account" alias="Account"/>
</typeAliases>

Configuration当中的:

protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
  protected final InterceptorChain interceptorChain = new InterceptorChain();
  protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
  protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
  protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();

4:标签Mappers

mybatis-config.xml中的s标签:

<mappers>
        <!--<package name=""-->
        <mapper resource="UserDAOMapper.xml"/>
        <mapper resource="AccountDAOMapper.xml"/>
    </mappers>

Configuration当中的:

protected final Set<String> loadedResources = new HashSet<String>();

二:mapper.xml与Configuration属性的映射关系

Configuration当中的:

protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
  protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection");
  protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection");
  protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection");
  protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection");

caches,parameterMaps,resultMaps,MapperdStatement,keyGenerators 这些是把Mapper.xml文件中的内容进行了封装。

resultMaps:所有的Mapper.xml文件中resultMap标签。

parameterMaps:是对sql标签上的parameterMap是属性做了处理。

上边这些属性都加了S都代表了是复数,也就是他的数量不只一个。这玩意存储的不是公共的,而是所有的。里边存储了对于所有的Mapper.xml文件中的这些属性都封装到这里边了。

这些不仅仅要存还要用,所以是将他们存入到了一个Map中,他是有key的,他的key就是namespace.id。所以你就发现这一组。这些对象封装到Configuration对象中之后都是采用的Map<String,xxx>这样的形式,key是namespace.id的形式。

三:Configuration对象可以创建操作类对象

new 就是创造,这里边创造了很多Mybatis核心的对象

这个Configuration类是整个Mabatis当中的核心类,把不仅仅是把Mybatis其他涉及到的核心对象也创建出来,不仅仅是上述存储类对象,其中就包括Excuter,StatementHanler,ResultHandler,ParamerHandler

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
  }
  public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
      ResultHandler resultHandler, BoundSql boundSql) {
    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
  }
  public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }
  public Executor newExecutor(Transaction transaction) {
    return newExecutor(transaction, defaultExecutorType);
  }
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

四:Configuration对象的作用

作用一:封装Mybatis-Config.xml先关的内容。

environments属性,封装的environments标签

接下来图里边的是typeAliases标签(实体全限定类型和简称的映射)这个也在Configuration当中也有封装

Mappers标签,我们在Configuration当中也是有对象进行对应的。其中对应的是 Set loadResources

到这,Mybatis-config.xml所有的标签,我们在configuration对象当中就都可以找到了。

作用二:Configuration将xxxMapper.xml封装成了MapperStatment对象组放到了Configurantion对象中进行引用。

Configuration中的属性是Map<String,MappedStatement> mappedStatements 其中的String还是nameSpace.id

Configuration对象还包括:还有其他的结果集,参数,使用返回参数key(caches,parameterMaps,resultMaps,MapperdStatement,keyGenerators )等等。

作用三:他的第三个核心作用就是帮我们创建:Mybatis其他涉及到的核心对象也创建出来,所以我们认为他是Mybatis当中最为核心的对象。

在这里可以认为Configuration实现是这些对象的执行对象的工厂对象。

第二章:MappedStatement对象

一:MappedStatement属性

public final class MappedStatement {
  private String resource;
  private Configuration configuration;
  private String id;
  private Integer fetchSize;
  private Integer timeout;
  private StatementType statementType;
  private ResultSetType resultSetType;
  private SqlSource sqlSource;
  private Cache cache;
  private ParameterMap parameterMap;
  private List<ResultMap> resultMaps;
  private boolean flushCacheRequired;
  private boolean useCache;
  private boolean resultOrdered;
  private SqlCommandType sqlCommandType;
  private KeyGenerator keyGenerator;
  private String[] keyProperties;
  private String[] keyColumns;
  private boolean hasNestedResultMaps;
  private String databaseId;
  private Log statementLog;
  private LanguageDriver lang;
  private String[] resultSets;
  }

二:MappedStatement和Mapper.xml关系

MappedStatement对像,也是一个存储了对象,存储的是Mapper文件中的Statement也就是我们定义的SQL标签,其中封装的是我们Mapper文件中的一个个标签,举例来讲 其中一个标签就会被封装成MappedStatement对象

我们的标签当中肯定会有id的属性,在我们的MappedStatement当中也会有id的属性。id属性完全唯一,他存储的是namespace.id所以,也是唯一,注定了在一个Mabatis当中会有N个MapperStatement对象。

这里边的statementType是什么意思,指的就是普通,预编译,存储过程。默认使用的就是preparedStatement,所以在我们的SQL标签上也肯定有这个属性,这个属性默认一定是prepared

四:MappedStatement和Configuration对象关系

MappedStatement当中可以找到Configuration对象,Configurantion对象可以找到MapperdStatement对象,他俩互相引用,双向关联,可以互相找到。

尾声

什么时候创建Configuration什么时候创建MappedStatement,以及他与我们的SQLSessions(Mybatis核心功能)是怎么交互的呀?我们后续再讲,操作类对象我们下篇文章在进行分析。

操作类对象大致有一下几种:

Excutor

StatementHandler

ParameterHandler

ResultSetHandler

TypeHandler

这些对象是Configuration对象进行创建的。有了操作类对象之后,我们基于上述存储类对象,我们就可以对数据库进行相应的操作了。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5月前
|
SQL Java 数据库连接
Mybatis源码分析系列之第三篇:Mybatis的操作类型对象
Mybatis源码分析系列之第三篇:Mybatis的操作类型对象
|
1天前
|
SQL Java 数据库连接
15:MyBatis对象关系与映射结构-Java Spring
15:MyBatis对象关系与映射结构-Java Spring
15 4
|
17天前
|
XML Java 数据库连接
java对象有集合mybatis如何映射
java对象有集合mybatis如何映射
14 4
|
20天前
|
SQL Java 数据库连接
深度解析MyBatis核心:探寻其核心对象的精妙设计
深度解析MyBatis核心:探寻其核心对象的精妙设计
22 1
深度解析MyBatis核心:探寻其核心对象的精妙设计
|
2月前
|
Java 数据库连接 mybatis
在SpringBoot集成下,Mybatis的mapper代理对象究竟是如何生成的
在SpringBoot集成下,Mybatis的mapper代理对象究竟是如何生成的
20 0
|
4月前
|
SQL Java 数据库连接
MyBatis源码篇:mybatis拦截器源码分析
MyBatis源码篇:mybatis拦截器源码分析
|
4月前
|
缓存 Java 数据库连接
|
4月前
|
SQL Java 数据库连接
|
5月前
|
SQL Java 数据库连接
干翻Mybatis源码系列之第十一篇:Mybatis拦截器获取被拦截对象的方法和参数
干翻Mybatis源码系列之第十一篇:Mybatis拦截器获取被拦截对象的方法和参数
|
5月前
|
存储 设计模式 Java
Mybatis源码细节探究:二级缓存Cache对象是在什么时候创建的?
Mybatis源码细节探究:二级缓存Cache对象是在什么时候创建的?