暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

MyBatis之启动分析(一)

ytao 2021-09-27
163

前言

MyBatis 作为目前最常用的持久层框架之一,分析其源码,对我们的使用过程中可更好的运用它。本系列基于 mybatis-3.4.6
进行分析。MyBatis 的初始化工作就是解析主配置文件,映射配置文件以及注解信息。然后保存在 org.apache.ibatis.session.Configuration
,供后期执行数据请求的相关调用。Configuration
里有大量配置信息,在后面每涉及到一个相关配置,会进行详细的分析。

启动

  1. public static void main(String[] args) throws IOException {

  2. // 获取配置文件

  3. Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

  4. // 通过 SqlSessionFactoryBuilder 构建 sqlSession 工厂

  5. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

  6. // 获取 sqlSession 实例

  7. SqlSession sqlSession = sqlSessionFactory.openSession();


  8. reader.close();

  9. sqlSession.close();

  10. }

分析

SqlSessionFactoryBuilder 类

SqlSessionFactoryBuilder 的 build()
是Mybatis启动的初始化入口,使用builder模式加载配置文件。通过查看该类,使用方法重载,有以下9个方法:

方法重载最终实现处理的方法源码如下:

  1. public SqlSessionFactory build(Reader reader, String environment, Properties properties) {

  2. try {

  3. // 实例化 XMLConfigBuilder,用于读取配置文件信息

  4. XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

  5. // 解析配置信息,保存到 Configuration

  6. return build(parser.parse());

  7. } catch (Exception e) {

  8. throw ExceptionFactory.wrapException("Error building SqlSession.", e);

  9. } finally {

  10. ErrorContext.instance().reset();

  11. try {

  12. reader.close();

  13. } catch (IOException e) {

  14. // Intentionally ignore. Prefer previous error.

  15. }

  16. }

  17. }

  • environment 是指定加载环境,默认值为 null。

  • properties 是属性配置文件,默认值为 null。同时读取配置文件既可字符流读取,也支持字节流读取。

  1. public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {

  2. try {

  3. XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);

  4. return build(parser.parse());

  5. } catch (Exception e) {

  6. throw ExceptionFactory.wrapException("Error building SqlSession.", e);

  7. } finally {

  8. ErrorContext.instance().reset();

  9. try {

  10. inputStream.close();

  11. } catch (IOException e) {

  12. // Intentionally ignore. Prefer previous error.

  13. }

  14. }

  15. }

实例化 XMLConfigBuilder 类

通过 SqlSessionFactoryBuilder 中 XMLConfigBuilderparser=newXMLConfigBuilder(reader,environment,properties)
, 分析 XMLConfigBuilder实例化过程。该类中有四个变量:

  1. private boolean parsed;

  2. private final XPathParser parser;

  3. private String environment;

  4. private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  • parsed 是否解析,一次解析即可。用于标志配置文件只解析一次, true
    为已解析过。

  • parser 解析配置的解析器

  • environment 加载环境,即 SqlSessionFactoryBuilder
     中的 environment

  • localReflectorFactory 用于创建和缓存 Reflector
    对象,一个类对应一个 Reflector
    。因为参数处理、结果映射等操作时,会涉及大量的反射操作。 DefaultReflectorFactory
    实现类比较简单,这里不再进行讲解。

XMLConfigBuilder构建函数实现:

  1. public XMLConfigBuilder(Reader reader, String environment, Properties props) {

  2. this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);

  3. }

实例化 XPathParser
 对象

首先实例化 XPathParser
对象,里面定义了5个变量:

  1. private final Document document;

  2. private boolean validation;

  3. private EntityResolver entityResolver;

  4. private Properties variables;

  5. private XPath xpath;

  • document 保存document对象

  • validation xml解析时是否验证文档

  • entityResolver 加载dtd文件

  • variables 配置文件定义的值

  • xpath Xpath对象,用于对XML文件节点的操作

XPathParser
对象构造函数有:

函数里面都处理了两件事:

  1. public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {

  2. commonConstructor(validation, variables, entityResolver);

  3. this.document = createDocument(new InputSource(reader));

  4. }

  • 初始化赋值,和创建 XPath
    对象,用于对XML文件节点的操作。

  1. private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {

  2. this.validation = validation;

  3. this.entityResolver = entityResolver;

  4. this.variables = variables;

  5. // 创建Xpath对象,用于对XML文件节点的操作

  6. XPathFactory factory = XPathFactory.newInstance();

  7. this.xpath = factory.newXPath();

  8. }

  • 创建 Document
    对象并赋值到 document
    变量, 这里属于Document创建的操作,不再详细讲述,不懂可以点击这里查看
    API (https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html?is-external=true)
  1. private Document createDocument(InputSource inputSource) {

  2. // important: this must only be called AFTER common constructor

  3. try {

  4. // 实例化 DocumentBuilderFactory 对象,用于创建 DocumentBuilder 对象

  5. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  6. // 是否校验文档

  7. factory.setValidating(validation);

  8. // 设置 DocumentBuilderFactory 的配置

  9. factory.setNamespaceAware(false);

  10. factory.setIgnoringComments(true);

  11. factory.setIgnoringElementContentWhitespace(false);

  12. factory.setCoalescing(false);

  13. factory.setExpandEntityReferences(true);

  14. // 创建 DocumentBuilder

  15. DocumentBuilder builder = factory.newDocumentBuilder();

  16. builder.setEntityResolver(entityResolver);

  17. builder.setErrorHandler(new ErrorHandler() {

  18. @Override

  19. public void error(SAXParseException exception) throws SAXException {

  20. throw exception;

  21. }


  22. @Override

  23. public void fatalError(SAXParseException exception) throws SAXException {

  24. throw exception;

  25. }


  26. @Override

  27. public void warning(SAXParseException exception) throws SAXException {

  28. }

  29. });

  30. // 加载文件

  31. return builder.parse(inputSource);

  32. } catch (Exception e) {

  33. throw new BuilderException("Error creating document instance. Cause: " + e, e);

  34. }

  35. }

XMLConfigBuilder
构造函数赋值

  1. private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {

  2. super(new Configuration());

  3. ErrorContext.instance().resource("SQL Mapper Configuration");

  4. this.configuration.setVariables(props);

  5. this.parsed = false;

  6. this.environment = environment;

  7. this.parser = parser;

  8. }

  1. 初始化父类 BaseBuilder
    的值。

  2. 将外部值赋值给对象。

  3. 将实例化的 XPathParser
    赋值给 parser

最后返回 XMLConfigBuilder
对象。

解析 XMLConfigBuilder 对象

通过 XMLConfigBuilder.parse()
解析配置信息,保存至 Configuration
。解析详解在后面文章中进行分析。

  1. public Configuration parse() {

  2. // 是否解析过配置文件

  3. if (parsed) {

  4. throw new BuilderException("Each XMLConfigBuilder can only be used once.");

  5. }

  6. // 标志解析过,定义为 true

  7. parsed = true;

  8. // 解析 configuration 节点中的信息

  9. parseConfiguration(parser.evalNode("/configuration"));

  10. return configuration;

  11. }

创建 SqlSessionFactory

DefaultSqlSessionFactory
实现了 SqlSessionFactory
接口。通过上面解析得到的 Configuration
,调用 SqlSessionFactoryBuilder.build(Configurationconfig)
创建一个 DefaultSqlSessionFactory

  1. public SqlSessionFactory build(Configuration config) {

  2. return new DefaultSqlSessionFactory(config);

  3. }

实例化 DefaultSqlSessionFactory
的过程,就是将 Configuration
传递给 DefaultSqlSessionFactory
成员变量 configuration

  1. public DefaultSqlSessionFactory(Configuration configuration) {

  2. this.configuration = configuration;

  3. }

创建 SqlSession

通过调用 SqlSessionFactory.openSession()
创建 SqlSession

  1. public interface SqlSessionFactory {

  2. // 默认创建

  3. SqlSession openSession();


  4. SqlSession openSession(boolean autoCommit);

  5. SqlSession openSession(Connection connection);

  6. SqlSession openSession(TransactionIsolationLevel level);


  7. SqlSession openSession(ExecutorType execType);

  8. SqlSession openSession(ExecutorType execType, boolean autoCommit);

  9. SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);

  10. SqlSession openSession(ExecutorType execType, Connection connection);


  11. Configuration getConfiguration();


  12. }

  • autoCommit 是否自动提交事务,

  • level 事务隔离级别(共5个级别), 可查看相关源码

  • connection 连接

  • execType 执行器的类型: SIMPLE
    (不做特殊处理), REUSE
    (复用预处理语句), BATCH
    (会批量执行)

因为上面 DefaultSqlSessionFactory
实现了 SqlSessionFactory
接口,所以进入到 DefaultSqlSessionFactory
查看 openSession()

  1. public SqlSession openSession() {

  2. return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);

  3. }

openSession()
方法最终实现代码如下:

  1. private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {

  2. Transaction tx = null;

  3. try {

  4. // 获取configuration中的加载环境

  5. final Environment environment = configuration.getEnvironment();

  6. // 获取事务工厂

  7. final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);

  8. // 创建一个事务

  9. tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);

  10. // 生成一个处理器,事务保存在处理器 BaseExecutor 中

  11. final Executor executor = configuration.newExecutor(tx, execType);

  12. // 实例化一个 DefaultSqlSession,DefaultSqlSession实现了SqlSession接口

  13. return new DefaultSqlSession(configuration, executor, autoCommit);

  14. } catch (Exception e) {

  15. // 异常情况下关闭事务

  16. closeTransaction(tx); // may have fetched a connection so lets call close()

  17. throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);

  18. } finally {

  19. // 充值错误实例上下文

  20. ErrorContext.instance().reset();

  21. }

  22. }

生成处理器 Configuration.newExecutor(Transactiontransaction,ExecutorTypeexecutorType)

  1. public Executor newExecutor(Transaction transaction, ExecutorType executorType) {

  2. // 默认为 ExecutorType.SIMPLE

  3. executorType = executorType == null ? defaultExecutorType : executorType;

  4. executorType = executorType == null ? ExecutorType.SIMPLE : executorType;

  5. Executor executor;

  6. if (ExecutorType.BATCH == executorType) {

  7. executor = new BatchExecutor(this, transaction);

  8. } else if (ExecutorType.REUSE == executorType) {

  9. executor = new ReuseExecutor(this, transaction);

  10. } else {

  11. executor = new SimpleExecutor(this, transaction);

  12. }

  13. if (cacheEnabled) {

  14. executor = new CachingExecutor(executor);

  15. }

  16. executor = (Executor) interceptorChain.pluginAll(executor);

  17. return executor;

  18. }

ExecutorType.SIMPLE
为例, BatchExecutor
, ReuseExecutor
同理:至此,mybatis的启动流程大致简单的介绍到这里,对mybatis的启动初始化有个大致了解。接下将会针对单独模块进行详细分析。


文章转载自ytao,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论