Mybatis-持久層的框架,功能是非常強大的,對於移動網際網路的高併發 和 高效能是非常有利的,相對於Hibernate全自動的ORM框架,Mybatis簡單,易於學習,sql編寫在xml檔案中,和程式碼分離,易於維護,屬於半ORM框架,對於面向使用者層面的網際網路業務效能和併發,可以通過sql優化解決一些問題。
現如今大部分公司都在使用Mybatis,所以我們要理解框架底層的原理。閒話不多說。
Mybatis框架的核心入口 是SqlSessionFactory介面,我們先看一下它的程式碼
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(); }
SqlSessionFactory介面很多過載的openSession方法,返回sqlSession型別 物件, 還有Configuration類(這個類非常強大,下面會梳理),我們先看一下SqlSession的程式碼
public interface SqlSession extends Closeable { <T> T selectOne(String statement); <T> T selectOne(String statement, Object parameter); <E> List<E> selectList(String statement); <E> List<E> selectList(String statement, Object parameter); <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds); <K, V> Map<K, V> selectMap(String statement, String mapKey); <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey); <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); <T> Cursor<T> selectCursor(String statement); <T> Cursor<T> selectCursor(String statement, Object parameter); <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds); void select(String statement, Object parameter, ResultHandler handler); void select(String statement, ResultHandler handler); List<BatchResult> flushStatements(); /** * Closes the session */ @Override void close(); void clearCache(); Configuration getConfiguration(); <T> T getMapper(Class<T> type); Connection getConnection(); }
只是展示了部分程式碼,但我們可以看到,sqlSeesion裡面 大多數方法是 增刪改查的執行方法,包括查詢返回不同的資料結構,比較注意的是clearCache()和getConnection()方法,一個是清楚快取,一個是獲取連線,獲取資料庫連線在這不在描述, 為什麼要注意清楚快取那,因為mybatis框架是實現了 快取的,分為一級快取,二級快取,當增刪改的時候就會呼叫此方法,刪除快取(後續會專門寫一篇文章來分析Mybatis快取),先在這給大家熟悉一下。
上面的SqlSessionFactory和SqlSeesion都是介面,我們在看一下實現類DefaultSqlSessionFactory和DefaultSqlSession,下面展示DefaultSqlSessionFactory的比較核心的程式碼
1 private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { 2 Transaction tx = null; 3 try { 4 final Environment environment = configuration.getEnvironment(); 5 final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); 6 tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); 7 final Executor executor = configuration.newExecutor(tx, execType); 8 return new DefaultSqlSession(configuration, executor, autoCommit); 9 } catch (Exception e) { 10 closeTransaction(tx); // may have fetched a connection so lets call close() 11 throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); 12 } finally { 13 ErrorContext.instance().reset(); 14 } 15 }
其實SqlSessionFactory中的多個過載openSeesion方法最終都是執行的這個方法,我們可以看到這個方法中 通過 configuration屬性 獲取到Executor 執行器物件,DefaultSqlSession構造器把這configuration和executor當成構造引數,初始化建立一個 DefaultSqlSession物件,然後我們在展示一下DefaultSqlSession程式碼中的大家一看就理解的程式碼
1 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { 2 try { 3 MappedStatement ms = configuration.getMappedStatement(statement); 4 return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); 5 } catch (Exception e) { 6 throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); 7 } finally { 8 ErrorContext.instance().reset(); 9 } 10 }
看到這個方法大家估計就會看明白了,底層執行的就是 通過Executor 物件執行的 查詢, 通過configuration獲取到 要執行的sql,獲取到我們需要的結果。
從上面程式碼可以看出 Configuration 類無處不在,那我們就去看一下原始碼
1 public class Configuration { 2 3 protected Environment environment; 4 5 protected boolean safeRowBoundsEnabled; 6 protected boolean safeResultHandlerEnabled = true; 7 protected boolean mapUnderscoreToCamelCase; 8 protected boolean aggressiveLazyLoading; 9 protected boolean multipleResultSetsEnabled = true; 10 protected boolean useGeneratedKeys; 11 protected boolean useColumnLabel = true; 12 protected boolean cacheEnabled = true; 13 protected boolean callSettersOnNulls; 14 protected boolean useActualParamName = true; 15 protected boolean returnInstanceForEmptyRow; 16 17 protected String logPrefix; 18 protected Class <? extends Log> logImpl; 19 protected Class <? extends VFS> vfsImpl; 20 protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION; 21 protected JdbcType jdbcTypeForNull = JdbcType.OTHER; 22 protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" })); 23 protected Integer defaultStatementTimeout; 24 protected Integer defaultFetchSize; 25 protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE; 26 protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL; 27 protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE; 28 29 protected Properties variables = new Properties(); 30 protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory(); 31 protected ObjectFactory objectFactory = new DefaultObjectFactory(); 32 protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory(); 33 34 protected boolean lazyLoadingEnabled = false; 35 protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL 36 37 protected String databaseId; 38 /** 39 * Configuration factory class. 40 * Used to create Configuration for loading deserialized unread properties. 41 * 42 * @see <a href='https://code.google.com/p/mybatis/issues/detail?id=300'>Issue 300 (google code)</a> 43 */ 44 protected Class<?> configurationFactory; 45 46 protected final MapperRegistry mapperRegistry = new MapperRegistry(this); 47 protected final InterceptorChain interceptorChain = new InterceptorChain(); 48 protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(); 49 protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry(); 50 protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry(); 51 52 protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection"); 53 protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection"); 54 protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection"); 55 protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection"); 56 protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection"); 57 58 protected final Set<String> loadedResources = new HashSet<String>(); 59 protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers"); 60 61 protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<XMLStatementBuilder>(); 62 protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<CacheRefResolver>(); 63 protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>(); 64 protected final Collection<MethodResolver> incompleteMethods = new LinkedList<MethodResolver>(); 65 66 /* 67 * A map holds cache-ref relationship. The key is the namespace that 68 * references a cache bound to another namespace and the value is the 69 * namespace which the actual cache is bound to. 70 */ 71 protected final Map<String, String> cacheRefMap = new HashMap<String, String>();}
上面的程式碼都是 Configuration類中的屬性值,上面的boolean 型別的屬性 都是一些配置的屬性,比如useGeneratedKeys是否開啟使用返回主鍵,cacheEnabled是否開啟快取等等,下面的Map型別的 就是儲存一些我們專案中需要編寫的sql.xml檔案,我們可以通過變數名大致推測出來儲存的結果,比如typeAliasRegistry 儲存的別名,mappedStatements 儲存的sql,resultMaps儲存的結果等,當然這些map的key對應的就是 sql.xml中的唯一的id,分析到現在,我們大致知道Mybatis框架底層的執行原理了。
但是,這時候就有個疑問了,入口類是SqlSessionFactory,那是怎麼載入資源的那,我們通過名稱尋找原始碼,可以找到一個SqlSessionFactoryBuilder(這些開發開源框架的牛人們不管技術NB,對類的命名也是很值的大家效仿的),builder--載入, 說明這個類就是載入 SqlSessionFactory,我們看一下程式碼
1 public class SqlSessionFactoryBuilder { 2 3 public SqlSessionFactory build(Reader reader) { 4 return build(reader, null, null); 5 } 6 7 public SqlSessionFactory build(Reader reader, String environment) { 8 return build(reader, environment, null); 9 } 10 11 public SqlSessionFactory build(Reader reader, Properties properties) { 12 return build(reader, null, properties); 13 } 14 15 public SqlSessionFactory build(Reader reader, String environment, Properties properties) { 16 try { 17 XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties); 18 return build(parser.parse()); 19 } catch (Exception e) { 20 throw ExceptionFactory.wrapException("Error building SqlSession.", e); 21 } finally { 22 ErrorContext.instance().reset(); 23 try { 24 reader.close(); 25 } catch (IOException e) { 26 // Intentionally ignore. Prefer previous error. 27 } 28 } 29 } 30 31 public SqlSessionFactory build(InputStream inputStream) { 32 return build(inputStream, null, null); 33 } 34 35 public SqlSessionFactory build(InputStream inputStream, String environment) { 36 return build(inputStream, environment, null); 37 } 38 39 public SqlSessionFactory build(InputStream inputStream, Properties properties) { 40 return build(inputStream, null, properties); 41 } 42 43 public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { 44 try { 45 XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); 46 return build(parser.parse()); 47 } catch (Exception e) { 48 throw ExceptionFactory.wrapException("Error building SqlSession.", e); 49 } finally { 50 ErrorContext.instance().reset(); 51 try { 52 inputStream.close(); 53 } catch (IOException e) { 54 // Intentionally ignore. Prefer previous error. 55 } 56 } 57 } 58 59 public SqlSessionFactory build(Configuration config) { 60 return new DefaultSqlSessionFactory(config); 61 } 62 63 }
檢視程式碼中的build方法,可以看出是 通過流來載入xml檔案 ,包括mybatis的配置檔案和 sql.xml檔案,返回一個DefaultSqlSessionFactory 物件。
本篇檔案只是介紹了mybatis的底層執行原理,喜歡深入瞭解的可以自己去深入瞭解一下。
以上是個人理解,歡迎大家來討論,不喜勿噴!謝謝!!
如轉載,請註明轉載地址,謝謝