MyBatis 源码系列:MyBatis 体系结构、六大解析器

2024-03-04 0 1,375

体系结构

MyBatis是一个持久框架,其体系结构分为三层基础支持层、核心处理层和接口层。

基础支持层包括数据源模块事务管理模块缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块和解析器模块。这些模块为MyBatis提供了基础功能,为核心处理层提供了良好的支撑。

核心处理层包括配置解析、参数映射、SQL解析、SQL执行、结果集映射和插件。这些组件共同完成了MyBatis的核心处理逻辑,包括将SQL语句与输入参数进行映射,解析SQL语句,执行SQL语句,并将结果映射回Java对象等。

接口层是MyBatis与上层应用交互的桥梁,包括SqlSession接口。SqlSession是MyBatis中最重要的接口之一,它定义了MyBatis保留给应用的API,用于执行各种数据库操作,如查询、插入、更新和删除等。

在MyBatis的体系结构中,还有一个重要的组成部分是全局配置文件。全局配置文件包含了MyBatis的运行环境等信息,通过解析全局配置文件,MyBatis可以完成基本配置的初始化,并根据配置信息实例化相应的组件。

总的来说,MyBatis的体系结构是一个层次分明、模块化的结构,各层之间相互依赖、协同工作,共同完成了MyBatis的核心功能和操作数据库的逻辑。通过这种结构,MyBatis能够有效地封装底层的JDBC操作,让用户专注于SQL语句的编写和数据库操作,提高了开发效率和代码的可维护性。

MyBatis 源码系列:MyBatis 体系结构、六大解析器

六大解析器

MyBatis的六大解析器Builder分别是:

  1. XMLConfigBuilder:用于构建 MyBatis 的配置信息,包括数据源、事务管理器等信息。
  2. XMLMapperBuilder:用于构建 Mapper 的 XML 配置文件。该 Builder 读取 Mapper 的 XML 文件,将其解析为 SqlSessionFactory 的一个实例,以便在后续的操作中使用。
  3. MapperBuilderAssistant:用于协助构建 Mapper 的 XML 配置文件。该 Builder 提供了一系列方法,用于简化 Mapper XML 文件的构建过程。
  4. XMLStatementBuilder:用于构建 SQL 语句的 Builder。该 Builder 负责解析 SQL 语句,并将其转换为 MyBatis 可以执行的内部表示形式。
  5. XMLScriptBuilder:用于构建 XML 脚本的 Builder。该 Builder 提供了一些方法,用于构建执行 DDL(数据定义语言)操作的 XML 脚本,例如创建表、视图等。
  6. SqlSourceBuilder:用于构建 SQL 语句的源代码。该 Builder 读取 MyBatis 的映射文件中的 <sql> 标签,将其解析为 SqlSource 对象,以便在执行 SQL 语句时使用。

MyBatis 源码系列:MyBatis 体系结构、六大解析器

注意:最终解析的都会存入 Configuration 对象中

package org.apache.ibatis.session;

/**
 * @author Clinton Begin
 */
public class Configuration {

  protected Environment environment;

  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;
  protected boolean shrinkWhitespacesInSql;
  protected boolean nullableOnForEach;
  protected boolean argNameBasedConstructorAutoMapping;

  ...
}

MyBatis 源码系列:MyBatis 体系结构、六大解析器

全部代码

SQL 脚本

create database test;
create table test.user
(
    id          int auto_increment
        primary key,
    user_name   varchar(50) not null,
    create_time datetime    not null
);

mybaits-cofig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"></properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <plugins>
        <plugin interceptor="com.mcode.plugin.ExamplePlugin" ></plugin>
    </plugins>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--//  mybatis内置了JNDI、POOLED、UNPOOLED三种类型的数据源,其中POOLED对应的实现为org.apache.ibatis.datasource.pooled.PooledDataSource,它是mybatis自带实现的一个同步、线程安全的数据库连接池 一般在生产中,我们会使用c3p0或者druid连接池-->
            <dataSource type="POOLED">
            <property name="driver" value="${mysql.driverClass}"/>
            <property name="url" value="${mysql.jdbcUrl}"/>
            <property name="username" value="${mysql.user}"/>
            <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--1.必须保证接口名(例如IUserDao)和xml名(IUserDao.xml)相同,还必须在同一个包中-->
        <package name="com.mcode.mapper"/>

        <!--2.不用保证同接口同包同名
         <mapper resource="com/mybatis/mappers/EmployeeMapper.xml"/>

        3.保证接口名(例如IUserDao)和xml名(IUserDao.xml)相同,还必须在同一个包中
        <mapper class="com.mybatis.dao.EmployeeMapper"/>

        4.不推荐:引用网路路径或者磁盘路径下的sql映射文件 file:///var/mappers/AuthorMapper.xml
         <mapper url="file:E:/Study/myeclipse/_03_Test/src/cn/sdut/pojo/PersonMapper.xml"/>-->
    </mappers>
</configuration>

db.properties

mysql.driverClass=com.mysql.cj.jdbc.Driver
mysql.jdbcUrl=jdbc:mysql://127.0.0.1/test?characterEncoding=utf8
mysql.user= root
mysql.password= 123456

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.mcode.mapper.UserMapper">
    <cache ></cache>
    <!-- Mybatis 是如何将 sql 执行结果封装为目标对象并返回的?都有哪些映射形式?-->
    <resultMap id="result" type="com.mcode.entity.User">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
        <result column="create_time" jdbcType="DATE" property="createTime"/>
        <!--<collection property="" select=""-->

    </resultMap>
    <!--namespace根据自己需要创建的的mapper的路径和名称填写-->
    <select id="selectById" resultMap="result">
        select * from user
        <where>
            <if test="id > 0">
                and id = #{id}
            </if>
        </where>
    </select>
</mapper>

User.java

package com.mcode.entity;

import java.time.LocalDateTime;

/**
 * ClassName: User
 * Package: com.mcode.entity
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
public class User {
    private int id;
    private String userName;

    private LocalDateTime createTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }
}

UserMapper.java

package com.mcode.entity;

import java.time.LocalDateTime;

/**
 * ClassName: User
 * Package: com.mcode.entity
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
public class User {
    private int id;
    private String userName;

    private LocalDateTime createTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }
}

ExamplePlugin.java

package com.mcode.plugin;

/**
 * ClassName: ExamplePlugin
 * Package: com.mcode.plugin
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;


@Intercepts({@Signature( type= Executor.class,  method = "query", args ={
        MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
})})
public class ExamplePlugin implements Interceptor {

    //  分页   读写分离    Select  增删改

    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("代理");
        Object[] args = invocation.getArgs();
        MappedStatement ms= (MappedStatement) args[0];
        // 执行下一个拦截器、直到尽头
        return invocation.proceed();
    }

}

App.java

package com.mcode;

import com.mcode.entity.User;
import com.mcode.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        String resource = "mybatis-config.xml";
        Reader reader;
        try {
            //将XML配置文件构建为Configuration配置类
            reader = Resources.getResourceAsReader(resource);
            // 通过加载配置文件流构建一个SqlSessionFactory  DefaultSqlSessionFactory
            SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
            // 数据源 执行器  DefaultSqlSession
            SqlSession session = sqlMapper.openSession();
            sqlMapper.getConfiguration();
            try {
                UserMapper mapper = session.getMapper(UserMapper.class);
                System.out.println(mapper.getClass());
                User user = mapper.selectById(1);
                System.out.println(user.getUserName());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 MyBatis 源码系列:MyBatis 体系结构、六大解析器 http://www.20zxx.cn/809189/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务