這篇文章主要講解了“MyBatis啟動(dòng)以及各種類的作用”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“MyBatis啟動(dòng)以及各種類的作用”吧!
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供民豐網(wǎng)站建設(shè)、民豐做網(wǎng)站、民豐網(wǎng)站設(shè)計(jì)、民豐網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、民豐企業(yè)網(wǎng)站模板建站服務(wù),十年民豐做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
MyBatis 作為目前最常用的持久層框架之一,分析其源碼,對(duì)我們的使用過程中可更好的運(yùn)用它。本系列基于mybatis-3.4.6
進(jìn)行分析。 MyBatis 的初始化工作就是解析主配置文件,映射配置文件以及注解信息。然后保存在org.apache.ibatis.session.Configuration
,供后期執(zhí)行數(shù)據(jù)請(qǐng)求的相關(guān)調(diào)用。 Configuration
里有大量配置信息,在后面每涉及到一個(gè)相關(guān)配置,會(huì)進(jìn)行詳細(xì)的分析。
public static void main(String[] args) throws IOException { // 獲取配置文件 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); // 通過 SqlSessionFactoryBuilder 構(gòu)建 sqlSession 工廠 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 獲取 sqlSession 實(shí)例 SqlSession sqlSession = sqlSessionFactory.openSession(); reader.close(); sqlSession.close(); }
SqlSessionFactoryBuilder 的build()
是Mybatis啟動(dòng)的初始化入口,使用builder模式加載配置文件。 通過查看該類,使用方法重載,有以下9個(gè)方法:
方法重載最終實(shí)現(xiàn)處理的方法源碼如下:
public SqlSessionFactory build(Reader reader, String environment, Properties properties) { try { // 實(shí)例化 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. } } }
environment 是指定加載環(huán)境,默認(rèn)值為 null。
properties 是屬性配置文件,默認(rèn)值為 null。 同時(shí)讀取配置文件既可字符流讀取,也支持字節(jié)流讀取。
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實(shí)例化過程。 該類中有四個(gè)變量:
private boolean parsed; private final XPathParser parser; private String environment; private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
parsed 是否解析,一次解析即可。用于標(biāo)志配置文件只解析一次,true
為已解析過。
parser 解析配置的解析器
environment 加載環(huán)境,即 SqlSessionFactoryBuilder
中的 environment
localReflectorFactory 用于創(chuàng)建和緩存Reflector
對(duì)象,一個(gè)類對(duì)應(yīng)一個(gè)Reflector
。因?yàn)閰?shù)處理、結(jié)果映射等操作時(shí),會(huì)涉及大量的反射操作。DefaultReflectorFactory
實(shí)現(xiàn)類比較簡(jiǎn)單,這里不再進(jìn)行講解。
XMLConfigBuilder構(gòu)建函數(shù)實(shí)現(xiàn):
public XMLConfigBuilder(Reader reader, String environment, Properties props) { this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props); }
XPathParser
對(duì)象首先實(shí)例化 XPathParser
對(duì)象,里面定義了5個(gè)變量:
private final Document document; private boolean validation; private EntityResolver entityResolver; private Properties variables; private XPath xpath;
document 保存document對(duì)象
validation xml解析時(shí)是否驗(yàn)證文檔
entityResolver 加載dtd文件
variables 配置文件定義<properties>的值
xpath Xpath對(duì)象,用于對(duì)XML文件節(jié)點(diǎn)的操作
XPathParser
對(duì)象構(gòu)造函數(shù)有:
函數(shù)里面都處理了兩件事:
public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) { commonConstructor(validation, variables, entityResolver); this.document = createDocument(new InputSource(reader)); }
初始化賦值,和創(chuàng)建XPath
對(duì)象,用于對(duì)XML文件節(jié)點(diǎn)的操作。
private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) { this.validation = validation; this.entityResolver = entityResolver; this.variables = variables; // 創(chuàng)建Xpath對(duì)象,用于對(duì)XML文件節(jié)點(diǎn)的操作 XPathFactory factory = XPathFactory.newInstance(); this.xpath = factory.newXPath(); }
創(chuàng)建Document
對(duì)象并賦值到document
變量, 這里屬于Document創(chuàng)建的操作,不再詳細(xì)講述,不懂可以點(diǎn)擊這里查看API
private Document createDocument(InputSource inputSource) { // important: this must only be called AFTER common constructor try { // 實(shí)例化 DocumentBuilderFactory 對(duì)象,用于創(chuàng)建 DocumentBuilder 對(duì)象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 是否校驗(yàn)文檔 factory.setValidating(validation); // 設(shè)置 DocumentBuilderFactory 的配置 factory.setNamespaceAware(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(false); factory.setCoalescing(false); factory.setExpandEntityReferences(true); // 創(chuàng)建 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
構(gòu)造函數(shù)賦值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
的值。
將外部值賦值給對(duì)象。
將實(shí)例化的XPathParser
賦值給parser
。
最后返回XMLConfigBuilder
對(duì)象。
通過 XMLConfigBuilder.parse()
解析配置信息,保存至Configuration
。解析詳解在后面文章中進(jìn)行分析。
public Configuration parse() { // 是否解析過配置文件 if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } // 標(biāo)志解析過,定義為 true parsed = true; // 解析 configuration 節(jié)點(diǎn)中的信息 parseConfiguration(parser.evalNode("/configuration")); return configuration; }
DefaultSqlSessionFactory
實(shí)現(xiàn)了SqlSessionFactory
接口。 通過上面解析得到的Configuration
,調(diào)用SqlSessionFactoryBuilder.build(Configuration config)
創(chuàng)建一個(gè) DefaultSqlSessionFactory
。
public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); }
實(shí)例化DefaultSqlSessionFactory
的過程,就是將Configuration
傳遞給DefaultSqlSessionFactory
成員變量configuration
。
public DefaultSqlSessionFactory(Configuration configuration) { this.configuration = configuration; }
通過調(diào)用SqlSessionFactory.openSession()
創(chuàng)建SqlSession
。
public interface SqlSessionFactory { // 默認(rèn)創(chuàng)建 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(); }
autoCommit 是否自動(dòng)提交事務(wù),
level 事務(wù)隔離級(jí)別(共5個(gè)級(jí)別), 可查看相關(guān)源碼
connection 連接
execType 執(zhí)行器的類型:SIMPLE
(不做特殊處理), REUSE
(復(fù)用預(yù)處理語句), BATCH
(會(huì)批量執(zhí)行)
因?yàn)樯厦?code>DefaultSqlSessionFactory實(shí)現(xiàn)了SqlSessionFactory
接口,所以進(jìn)入到DefaultSqlSessionFactory
查看openSession()
。
public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
openSession()
方法最終實(shí)現(xiàn)代碼如下:
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { // 獲取configuration中的加載環(huán)境 final Environment environment = configuration.getEnvironment(); // 獲取事務(wù)工廠 final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); // 創(chuàng)建一個(gè)事務(wù) tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); // 生成一個(gè)處理器,事務(wù)保存在處理器 BaseExecutor 中 final Executor executor = configuration.newExecutor(tx, execType); // 實(shí)例化一個(gè) DefaultSqlSession,DefaultSqlSession實(shí)現(xiàn)了SqlSession接口 return new DefaultSqlSession(configuration, executor, autoCommit); } catch (Exception e) { // 異常情況下關(guān)閉事務(wù) closeTransaction(tx); // may have fetched a connection so lets call close() throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { // 充值錯(cuò)誤實(shí)例上下文 ErrorContext.instance().reset(); } }
生成處理器Configuration.newExecutor(Transaction transaction, ExecutorType executorType)
:
public Executor newExecutor(Transaction transaction, ExecutorType executorType) { // 默認(rèn)為 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啟動(dòng)以及各種類的作用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)MyBatis啟動(dòng)以及各種類的作用這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
文章名稱:MyBatis啟動(dòng)以及各種類的作用
網(wǎng)站鏈接:http://chinadenli.net/article28/ppcicp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、全網(wǎng)營(yíng)銷推廣、微信小程序、手機(jī)網(wǎng)站建設(shè)、企業(yè)建站、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)