Mybatis操作主體流程

親吻昨日的陽光發表於2016-10-18

完整的時序圖可以開啟我的雲筆記進行檢視,對瀏覽器檢視比例進行縮放為250%即可

1 Mybatis操作主體流程

  • 定位配置檔案的位置
  • 構建sessionFactory
  • 獲取資料庫操作會話
  • 建立資料庫連線並執行資料庫操作

1.1 定位配置檔案位置

使用org.apache.ibatis.io.Resources.getResourceAsReader(String)定位mybatis配置檔案的位置,獲得檔案的輸入流。

Created with Raphaël 2.1.0ReaderReaderResourcesResourcesInputStreamReaderInputStreamReaderInputStreamInputStreamClassLoaderWrapperClassLoaderWrapperClassLoaderClassLoadergetResourceAsReader()getResourceAsReader()''getResourceAsStream()getResourceAsStream()getResourceAsStream()''getResourceAsReadernew InputStreamReader()

1.2構建SqlSessionFactory

構建SqlSessionFactory的時序圖,使用SqlSessionFactoryBuilder建立SqlSessionFactory物件

Created with Raphaël 2.1.0SqlSessionFactoryBuilderSqlSessionFactoryBuilderXMLConfigBuilderXMLConfigBuilderXPathParserXPathParserDocumentBuilderDocumentBuilderDOMParserDOMParserDocumentDocumentConfigurationConfigurationSqlSessionFactorySqlSessionFactorybuild(reader)XMLConfigBuilder(XPathParser)createDocument()parse()getDocument()new XPathParser()new XMLConfigBuilder()parse()parseConfiguration()build(Configuration)

根據時序圖可以看得出,建立sessionFactory需要

  • 將讀入的配置檔案流解析為Document物件
  • 將Document物件解析為Configuration物件
  • 使用Configuration物件,通過build()方法完成對SqlSessionFactory物件的建立。

1.3 獲取資料庫操作的會話

Created with Raphaël 2.1.0SqlSessionFactorySqlSessionFactoryDefaultSqlSessionFactoryDefaultSqlSessionFactorySqlSessionSqlSessionopenSession()openSessionFromDataSource()new DefaultSqlSession()

1.4 獲取介面例項

Created with Raphaël 2.1.0SqlSessionSqlSessionDefaultSqlSessionDefaultSqlSessionConfigurationConfigurationMapperRegistryMapperRegistryProxyProxyUserMapperUserMappergetMapper()getMapper()getMapper()newInstance()Proxy.newProxyInstance()
Created with Raphaël 2.1.0UserMapperUserMapperMapperProxyMapperProxyMapperMethodMapperMethodDefaultSqlSessionDefaultSqlSessionCachingExecutorCachingExecutorSimpleExecutorSimpleExecutorBaseExecutorBaseExecutorPreparedStatementHandlerPreparedStatementHandlerPreparedStatementPreparedStatementDefaultResultSetHandlerDefaultResultSetHandlergetUserById()execute()selectOne()selectList()query()query()queryFromDatabase()doQuery()prepareStatement()getConnection()prepare()query()execute()handleResultSets()''

在執行具體的
org.apache.ibatis.executor.SimpleExecutor.prepareStatement(StatementHandler, Log)處連線資料庫,檢查是否能連線成功

資料庫連線時序圖

Created with Raphaël 2.1.0SimpleExecutorSimpleExecutorBaseExecutorBaseExecutorJdbcTransactionJdbcTransactionDataSourceDataSourceUnpooledDataSourceUnpooledDataSourceDriverManagerDriverManagerDriverInfoDriverInfogetConnection()getConnection()getConnection()openConnection()getConnection()popConnection()new PooledConnection()doGetConnection()getConnection()connect()newInstance()''

相關文章