问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Mybatis核心类SqlSessionFactory,看完我悟了

创作时间:
作者:
@小白创作中心

Mybatis核心类SqlSessionFactory,看完我悟了

引用
CSDN
1.
https://m.blog.csdn.net/m0_59236433/article/details/144403176

Mybatis的核心类SqlSessionFactory是Mybatis框架中非常重要的一个组件,它负责创建和管理SqlSession。本文将通过实例代码和源码剖析,深入讲解SqlSessionFactory的构建过程。

1. 实例代码

在实例代码中,我们在测试类中写了一个 init() 方法,里面包括了 SqlSessionFactory 的构建,分为两步:

  1. 读取配置文件 mybatis-config.xml 输入流
  2. 根据输入流构建 SqlSessionFactory
public void init() {
    // 定义mybatis全局配置文件
    String resource = "mybatis-config.xml";
    // 加载 mybatis 全局配置文件
    InputStream inputStream = null;
    try {
        inputStream = Resources.getResourceAsStream(resource);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 构建sqlSession的工厂
    sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

去掉 try-catch,也就两行代码:

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

2. 代码剖析

根据上面的时序图,我们分析根据源码分析每个步骤。

  1. 获取配置文件输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis.config.xml");

这里没什么好说的,就是获取配置文件的输入流。

  1. build(in)

这里的 in 就是上一步获取的输入流 inputStream。

public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
}

在进入到 build 方法:

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
        XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
        return build(parser.parse());
    } catch (Exception e) {
        throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
        ErrorContext.instance().reset();
        try {
            inputStream.close();
        } catch (IOException e) {
            // Intentionally ignore. Prefer previous error.
        }
    }
}
  1. XMLConfigBuilder(in)

这一段代码是为了解析我们的配置文件,配置文件是 XML形式 ,我在之前的博客介绍过解析 XML 的几种方式。

一种是基于树的结构来解析的称为DOM;另一种是基于事件流的形式称为SAX和(StAX)

两者各有优缺点,我这里不做详细说明,想了解的可以看我之前的文章。

而 Mybatis 使用的是 DOM 形式,并结合 XPath 来解析配置文件。

  1. parse()
public Configuration parse() {
    if (this.parsed) {
        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    } else {
        this.parsed = true;
        this.parseConfiguration(this.parser.evalNode("/configuration"));
        return this.configuration;
    }
}

/configuration 标签处开始解析。然后我们进入到 this.parseConfiguration() 方法中:

private void parseConfiguration(XNode root) {
    try {
        this.propertiesElement(root.evalNode("properties"));
        Properties settings = this.settingsAsProperties(root.evalNode("settings"));
        this.loadCustomVfs(settings);
        this.loadCustomLogImpl(settings);
        this.typeAliasesElement(root.evalNode("typeAliases"));
        this.pluginElement(root.evalNode("plugins"));
        this.objectFactoryElement(root.evalNode("objectFactory"));
        this.objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
        this.reflectorFactoryElement(root.evalNode("reflectorFactory"));
        this.settingsElement(settings);
        this.environmentsElement(root.evalNode("environments"));
        this.databaseIdProviderElement(root.evalNode("databaseIdProvider"));
        this.typeHandlerElement(root.evalNode("typeHandlers"));
        this.mapperElement(root.evalNode("mappers"));
    } catch (Exception var3) {
        throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + var3, var3);
    }
}

看到这是不是很熟悉了,这不就是mybatis-config.xml 配置文件里面的各个标签名嘛,是的,这就是解析该文件,然后全部放在 configuration 对象中。需要注意的是,这里的 configuration 对象不仅包括 mybatis-config.xml 文件内容,也包括 xxxMapper.xml 文件内容。

  1. build(configuration)

public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
}

就是去 new 了一个 DefaultSqlSessionFactory 对象,将 configuration 作为参数。

  1. DefaultSqlSessionFactory(configuration)
public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
}

3. 总结

至此,SqlSessionFactory 的创建过程就讲完了,总的来说,SqlSessionFactory 的构建过程主要包括以下几个步骤:

  1. 读取 mybatis-config.xml 配置文件
  2. 使用 XMLConfigBuilder 解析配置文件
  3. 构建 Configuration 对象
  4. 创建 DefaultSqlSessionFactory 实例

这个过程体现了 Mybatis 框架的核心设计理念:通过配置文件和 XML 解析,将 SQL 语句和 Java 对象进行映射,从而实现数据持久化操作。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号