MyBatis 做爲目前最經常使用的持久層框架之一,分析其源碼,對咱們的使用過程當中可更好的運用它。本系列基於mybatis-3.4.6
進行分析。
MyBatis 的初始化工做就是解析主配置文件,映射配置文件以及註解信息。而後保存在org.apache.ibatis.session.Configuration
,供後期執行數據請求的相關調用。
Configuration
裏有大量配置信息,在後面每涉及到一個相關配置,會進行詳細的分析。
html
public static void main(String[] args) throws IOException { // 獲取配置文件 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); // 經過 SqlSessionFactoryBuilder 構建 sqlSession 工廠 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 獲取 sqlSession 實例 SqlSession sqlSession = sqlSessionFactory.openSession(); reader.close(); sqlSession.close(); }
SqlSessionFactoryBuilder 的build()
是Mybatis啓動的初始化入口,使用builder模式加載配置文件。
經過查看該類,使用方法重載,有如下9個方法:
java
方法重載最終實現處理的方法源碼以下:sql
public SqlSessionFactory build(Reader reader, String environment, Properties properties) { try { // 實例化 XMLConfigBuilder,用於讀取配置文件信息 XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties); // 解析配置信息,保存到 Configuration return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { reader.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } }
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. } } }
經過 SqlSessionFactoryBuilder 中 XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties)
, 分析 XMLConfigBuilder實例化過程。
該類中有四個變量:apache
private boolean parsed; private final XPathParser parser; private String environment; private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
true
爲已解析過。SqlSessionFactoryBuilder
中的 environment
Reflector
對象,一個類對應一個Reflector
。由於參數處理、結果映射等操做時,會涉及大量的反射操做。DefaultReflectorFactory
實現類比較簡單,這裏再也不進行講解。XMLConfigBuilder構建函數實現:api
public XMLConfigBuilder(Reader reader, String environment, Properties props) { this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props); }
XPathParser
對象首先實例化 XPathParser
對象,裏面定義了5個變量:緩存
private final Document document; private boolean validation; private EntityResolver entityResolver; private Properties variables; private XPath xpath;
XPathParser
對象構造函數有:
函數裏面都處理了兩件事:session
public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) { commonConstructor(validation, variables, entityResolver); this.document = createDocument(new InputSource(reader)); }
XPath
對象,用於對XML文件節點的操做。private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) { this.validation = validation; this.entityResolver = entityResolver; this.variables = variables; // 建立Xpath對象,用於對XML文件節點的操做 XPathFactory factory = XPathFactory.newInstance(); this.xpath = factory.newXPath(); }
Document
對象並賦值到document
變量, 這裏屬於Document建立的操做,再也不詳細講述,不懂能夠點擊這裏查看APIprivate Document createDocument(InputSource inputSource) { // important: this must only be called AFTER common constructor try { // 實例化 DocumentBuilderFactory 對象,用於建立 DocumentBuilder 對象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 是否校驗文檔 factory.setValidating(validation); // 設置 DocumentBuilderFactory 的配置 factory.setNamespaceAware(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(false); factory.setCoalescing(false); factory.setExpandEntityReferences(true); // 建立 DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void warning(SAXParseException exception) throws SAXException { } }); // 加載文件 return builder.parse(inputSource); } catch (Exception e) { throw new BuilderException("Error creating document instance. Cause: " + e, e); } }
XMLConfigBuilder
構造函數賦值private XMLConfigBuilder(XPathParser parser, String environment, Properties props) { super(new Configuration()); ErrorContext.instance().resource("SQL Mapper Configuration"); this.configuration.setVariables(props); this.parsed = false; this.environment = environment; this.parser = parser; }
BaseBuilder
的值。XPathParser
賦值給parser
。最後返回XMLConfigBuilder
對象。mybatis
經過 XMLConfigBuilder.parse()
解析配置信息,保存至Configuration
。解析詳解在後面文章中進行分析。oracle
public Configuration parse() { // 是否解析過配置文件 if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } // 標誌解析過,定義爲 true parsed = true; // 解析 configuration 節點中的信息 parseConfiguration(parser.evalNode("/configuration")); return configuration; }
DefaultSqlSessionFactory
實現了SqlSessionFactory
接口。
經過上面解析獲得的Configuration
,調用SqlSessionFactoryBuilder.build(Configuration config)
建立一個 DefaultSqlSessionFactory
。app
public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); }
實例化DefaultSqlSessionFactory
的過程,就是將Configuration
傳遞給DefaultSqlSessionFactory
成員變量configuration
。
public DefaultSqlSessionFactory(Configuration configuration) { this.configuration = configuration; }
經過調用SqlSessionFactory.openSession()
建立SqlSession
。
public interface SqlSessionFactory { // 默認建立 SqlSession openSession(); SqlSession openSession(boolean autoCommit); SqlSession openSession(Connection connection); SqlSession openSession(TransactionIsolationLevel level); SqlSession openSession(ExecutorType execType); SqlSession openSession(ExecutorType execType, boolean autoCommit); SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level); SqlSession openSession(ExecutorType execType, Connection connection); Configuration getConfiguration(); }
SIMPLE
(不作特殊處理), REUSE
(複用預處理語句), BATCH
(會批量執行)由於上面DefaultSqlSessionFactory
實現了SqlSessionFactory
接口,因此進入到DefaultSqlSessionFactory
查看openSession()
。
public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
openSession()
方法最終實現代碼以下:
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { // 獲取configuration中的加載環境 final Environment environment = configuration.getEnvironment(); // 獲取事務工廠 final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); // 建立一個事務 tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); // 生成一個處理器,事務保存在處理器 BaseExecutor 中 final Executor executor = configuration.newExecutor(tx, execType); // 實例化一個 DefaultSqlSession,DefaultSqlSession實現了SqlSession接口 return new DefaultSqlSession(configuration, executor, autoCommit); } catch (Exception e) { // 異常狀況下關閉事務 closeTransaction(tx); // may have fetched a connection so lets call close() throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { // 充值錯誤實例上下文 ErrorContext.instance().reset(); } }
生成處理器Configuration.newExecutor(Transaction transaction, ExecutorType executorType)
:
public Executor newExecutor(Transaction transaction, ExecutorType executorType) { // 默認爲 ExecutorType.SIMPLE 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; }
以ExecutorType.SIMPLE
爲例, BatchExecutor
, ReuseExecutor
同理:
至此,mybatis的啓動流程大體簡單的介紹到這裏,對mybatis的啓動初始化有個大體瞭解。接下將會針對單獨模塊進行詳細分析。
我的博客: https://ytao.top
個人公衆號 ytao