前面的章節主要講mybatis如何解析配置文件,這些都是一次性的過程。從本章開始講解動態的過程,它們跟應用程序對mybatis的調用密切相關。本章先從sqlsession開始。 java
建立
正如其名,Sqlsession對應着一次數據庫會話。因爲數據庫回話不是永久的,所以Sqlsession的生命週期也不該該是永久的,相反,在你每次訪問數據庫時都須要建立它(固然並非說在Sqlsession裏只能執行一次sql,你能夠執行屢次,當一旦關閉了Sqlsession就須要從新建立它)。建立Sqlsession的地方只有一個,那就是SqlsessionFactory的openSession方法: sql
- public SqlSessionopenSession() {
- returnopenSessionFromDataSource(configuration.getDefaultExecutorType(),null, false);
- }
咱們能夠看到實際建立SqlSession的地方是openSessionFromDataSource,以下: 數據庫
- private SqlSessionopenSessionFromDataSource(ExecutorType execType, TransactionIsolationLevellevel, boolean autoCommit) {
-
- Connectionconnection = null;
-
- try {
-
- finalEnvironment environment = configuration.getEnvironment();
-
- final DataSourcedataSource = getDataSourceFromEnvironment(environment);
-
- TransactionFactory transactionFactory =getTransactionFactoryFromEnvironment(environment);
-
- connection = dataSource.getConnection();
-
- if (level != null) {
-
- connection.setTransactionIsolation(level.getLevel());
-
- }
-
- connection = wrapConnection(connection);
-
- Transaction tx = transactionFactory.newTransaction(connection,autoCommit);
-
- Executorexecutor = configuration.newExecutor(tx, execType);
-
- returnnewDefaultSqlSession(configuration, executor, autoCommit);
-
- } catch (Exceptione) {
-
- closeConnection(connection);
-
- throwExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
-
- } finally {
-
- ErrorContext.instance().reset();
-
- }
-
- }
能夠看出,建立sqlsession通過了如下幾個主要步驟: 緩存
1) 從配置中獲取Environment; session
2) 從Environment中取得DataSource; mybatis
3) 從Environment中取得TransactionFactory; app
4) 從DataSource裏獲取數據庫鏈接對象Connection; ui
5) 在取得的數據庫鏈接上建立事務對象Transaction; this
6) 建立Executor對象(該對象很是重要,事實上sqlsession的全部操做都是經過它完成的); spa
7) 建立sqlsession對象。
Executor的建立
Executor與Sqlsession的關係就像市長與書記,Sqlsession只是個門面,真正幹事的是Executor,Sqlsession對數據庫的操做都是經過Executor來完成的。與Sqlsession同樣,Executor也是動態建立的:
- public ExecutornewExecutor(Transaction transaction, ExecutorType executorType) {
-
- executorType = executorType == null ? defaultExecutorType :executorType;
-
- executorType = executorType == null ?ExecutorType.SIMPLE : executorType;
-
- Executor executor;
-
- if(ExecutorType.BATCH == executorType) {
- executor = new BatchExecutor(this,transaction);
- } elseif(ExecutorType.REUSE == executorType) {
- executor = new ReuseExecutor(this,transaction);
- } else {
- executor = newSimpleExecutor(this, transaction);
- }
-
- if (cacheEnabled) {
- executor = new CachingExecutor(executor);
- }
- executor =(Executor) interceptorChain.pluginAll(executor);
- return executor;
- }
能夠看出,若是不開啓cache的話,建立的Executor只是3中基礎類型之一,BatchExecutor專門用於執行批量sql操做,ReuseExecutor會重用statement執行sql操做,SimpleExecutor只是簡單執行sql沒有什麼特別的。開啓cache的話(默認是開啓的而且沒有任何理由去關閉它),就會建立CachingExecutor,它之前面建立的Executor做爲惟一參數。CachingExecutor在查詢數據庫前先查找緩存,若沒找到的話調用delegate(就是構造時傳入的Executor對象)從數據庫查詢,並將查詢結果存入緩存中。
Executor對象是能夠被插件攔截的,若是定義了針對Executor類型的插件,最終生成的Executor對象是被各個插件插入後的代理對象(關於插件會有後續章節專門介紹,敬請期待)。
Mapper
Mybatis官方手冊建議經過mapper對象訪問mybatis,由於使用mapper看起來更優雅,就像下面這樣:
- session = sqlSessionFactory.openSession();
- UserDao userDao= session.getMapper(UserDao.class);
- UserDto user =new UserDto();
- user.setUsername("iMbatis");
- user.setPassword("iMbatis");
- userDao.insertUser(user);
那麼這個mapper究竟是什麼呢,它是如何建立的呢,它又是怎麼與sqlsession等關聯起來的呢?下面爲你一一解答。
建立
表面上看mapper是在sqlsession裏建立的,但實際建立它的地方是MapperRegistry:
- public <T>T getMapper(Class<T> type, SqlSession sqlSession) {
- if (!knownMappers.contains(type))
- thrownewBindingException("Type " + type + " isnot known to the MapperRegistry.");
- try {
- returnMapperProxy.newMapperProxy(type, sqlSession);
- } catch (Exceptione) {
- thrownewBindingException("Error getting mapper instance. Cause: " + e, e);
- }
- }
能夠看到,mapper是一個代理對象,它實現的接口就是傳入的type,這就是爲何mapper對象能夠經過接口直接訪問。同時還能夠看到,建立mapper代理對象時傳入了sqlsession對象,這樣就把sqlsession也關聯起來了。咱們進一步看看MapperProxy.newMapperProxy(type,sqlSession);背後發生了什麼事情:
- publicstatic <T>T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
- ClassLoaderclassLoader = mapperInterface.getClassLoader();
- Class<?>[] interfaces = new Class[]{mapperInterface};
- MapperProxyproxy = new MapperProxy(sqlSession);
- return (T) Proxy.newProxyInstance(classLoader,interfaces, proxy);
- }
看起來沒什麼特別的,和其餘代理類的建立同樣,咱們重點關注一下MapperProxy的invoke方法
MapperProxy的invoke
咱們知道對被代理對象的方法的訪問都會落實到代理者的invoke上來,MapperProxy的invoke以下:
- public Objectinvoke(Object proxy, Method method, Object[] args) throws Throwable{
- if (method.getDeclaringClass()== Object.class) {
- return method.invoke(this, args);
- }
-
- finalClass<?> declaringInterface = findDeclaringInterface(proxy, method);
- finalMapperMethod mapperMethod = newMapperMethod(declaringInterface, method, sqlSession);
- final Objectresult = mapperMethod.execute(args);
-
- if (result ==null && method.getReturnType().isPrimitive()&& !method.getReturnType().equals(Void.TYPE)) {
- thrownewBindingException("Mapper method '" + method.getName() + "'(" + method.getDeclaringClass()
- + ") attempted toreturn null from a method with a primitive return type ("
- + method.getReturnType() + ").");
- }
- return result;
- }
能夠看到invoke把執行權轉交給了MapperMethod,咱們來看看MapperMethod裏又是怎麼運做的:
- public Objectexecute(Object[] args) {
- Objectresult = null;
- if(SqlCommandType.INSERT == type) {
- Objectparam = getParam(args);
- result= sqlSession.insert(commandName, param);
- } elseif(SqlCommandType.UPDATE == type) {
- Object param = getParam(args);
- result= sqlSession.update(commandName, param);
- } elseif(SqlCommandType.DELETE == type) {
- Objectparam = getParam(args);
- result= sqlSession.delete(commandName, param);
- } elseif(SqlCommandType.SELECT == type) {
- if (returnsVoid &&resultHandlerIndex != null) {
- executeWithResultHandler(args);
- } elseif (returnsList) {
- result = executeForList(args);
- } elseif (returnsMap) {
- result = executeForMap(args);
- } else {
- Object param = getParam(args);
- result = sqlSession.selectOne(commandName, param);
- }
- } else {
- thrownewBindingException("Unknown execution method for: " + commandName);
- }
- return result;
-
- }
能夠看到,MapperMethod就像是一個分發者,他根據參數和返回值類型選擇不一樣的sqlsession方法來執行。這樣mapper對象與sqlsession就真正的關聯起來了。
Executor
前面提到過,sqlsession只是一個門面,真正發揮做用的是executor,對sqlsession方法的訪問最終都會落到executor的相應方法上去。Executor分紅兩大類,一類是CacheExecutor,另外一類是普通Executor。Executor的建立前面已經介紹了,下面介紹下他們的功能:
CacheExecutor
CacheExecutor有一個重要屬性delegate,它保存的是某類普通的Executor,值在構照時傳入。執行數據庫update操做時,它直接調用delegate的update方法,執行query方法時先嚐試從cache中取值,取不到再調用delegate的查詢方法,並將查詢結果存入cache中。代碼以下:
- public Listquery(MappedStatement ms, Object parameterObject, RowBounds rowBounds,ResultHandler resultHandler) throws SQLException {
- if (ms != null) {
- Cachecache = ms.getCache();
- if (cache != null) {
- flushCacheIfRequired(ms);
- cache.getReadWriteLock().readLock().lock();
- try {
- if (ms.isUseCache() && resultHandler ==null) {
- CacheKey key = createCacheKey(ms, parameterObject, rowBounds);
- final List cachedList = (List)cache.getObject(key);
- if (cachedList != null) {
- returncachedList;
- } else {
- List list = delegate.query(ms,parameterObject, rowBounds, resultHandler);
- tcm.putObject(cache,key, list);
- return list;
- }
- } else {
- returndelegate.query(ms,parameterObject, rowBounds, resultHandler);
- }
- } finally {
- cache.getReadWriteLock().readLock().unlock();
- }
- }
- }
- returndelegate.query(ms,parameterObject, rowBounds, resultHandler);
- }
普通Executor
普通Executor有3類,他們都繼承於BaseExecutor,BatchExecutor專門用於執行批量sql操做,ReuseExecutor會重用statement執行sql操做,SimpleExecutor只是簡單執行sql沒有什麼特別的。下面以SimpleExecutor爲例:
- public ListdoQuery(MappedStatement ms, Object parameter, RowBounds rowBounds,ResultHandler resultHandler) throws SQLException {
- Statementstmt = null;
- try {
- Configuration configuration = ms.getConfiguration();
- StatementHandler handler = configuration.newStatementHandler(this, ms,parameter, rowBounds,resultHandler);
- stmt =prepareStatement(handler);
- returnhandler.query(stmt, resultHandler);
- } finally {
- closeStatement(stmt);
- }
- }
能夠看出,Executor本質上也是個甩手掌櫃,具體的事情原來是StatementHandler來完成的。
StatementHandler
當Executor將指揮棒交給StatementHandler後,接下來的工做就是StatementHandler的事了。咱們先看看StatementHandler是如何建立的。
建立
- publicStatementHandler newStatementHandler(Executor executor, MappedStatementmappedStatement,
- ObjectparameterObject, RowBounds rowBounds, ResultHandler resultHandler) {
- StatementHandler statementHandler = newRoutingStatementHandler(executor, mappedStatement,parameterObject,rowBounds, resultHandler);
- statementHandler= (StatementHandler) interceptorChain.pluginAll(statementHandler);
- returnstatementHandler;
- }
能夠看到每次建立的StatementHandler都是RoutingStatementHandler,它只是一個分發者,他一個屬性delegate用於指定用哪一種具體的StatementHandler。可選的StatementHandler有SimpleStatementHandler、PreparedStatementHandler和CallableStatementHandler三種。選用哪一種在mapper配置文件的每一個statement裏指定,默認的是PreparedStatementHandler。同時還要注意到StatementHandler是能夠被攔截器攔截的,和Executor同樣,被攔截器攔截後的對像是一個代理對象。因爲mybatis沒有實現數據庫的物理分頁,衆多物理分頁的實現都是在這個地方使用攔截器實現的,本文做者也實現了一個分頁攔截器,在後續的章節會分享給你們,敬請期待。
初始化
StatementHandler建立後須要執行一些初始操做,好比statement的開啓和參數設置、對於PreparedStatement還須要執行參數的設置操做等。代碼以下:
- private StatementprepareStatement(StatementHandler handler) throwsSQLException {
- Statementstmt;
- Connectionconnection = transaction.getConnection();
- stmt =handler.prepare(connection);
- handler.parameterize(stmt);
- return stmt;
- }
statement的開啓和參數設置沒什麼特別的地方,handler.parameterize卻是能夠看看是怎麼回事。handler.parameterize經過調用ParameterHandler的setParameters完成參數的設置,ParameterHandler隨着StatementHandler的建立而建立,默認的實現是DefaultParameterHandler:
- publicParameterHandler newParameterHandler(MappedStatement mappedStatement, ObjectparameterObject, BoundSql boundSql) {
- ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement,parameterObject,boundSql);
- parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
- returnparameterHandler;
- }
同Executor和StatementHandler同樣,ParameterHandler也是能夠被攔截的。
參數設置
DefaultParameterHandler裏設置參數的代碼以下:
- publicvoidsetParameters(PreparedStatement ps) throwsSQLException {
- ErrorContext.instance().activity("settingparameters").object(mappedStatement.getParameterMap().getId());
- List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
- if(parameterMappings != null) {
- MetaObject metaObject = parameterObject == null ? null :configuration.newMetaObject(parameterObject);
- for (int i = 0; i< parameterMappings.size(); i++) {
- ParameterMapping parameterMapping = parameterMappings.get(i);
- if(parameterMapping.getMode() != ParameterMode.OUT) {
- Object value;
- String propertyName = parameterMapping.getProperty();
- PropertyTokenizer prop = newPropertyTokenizer(propertyName);
- if (parameterObject == null) {
- value = null;
- } elseif (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())){
- value = parameterObject;
- } elseif (boundSql.hasAdditionalParameter(propertyName)){
- value = boundSql.getAdditionalParameter(propertyName);
- } elseif(propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)
- && boundSql.hasAdditionalParameter(prop.getName())){
- value = boundSql.getAdditionalParameter(prop.getName());
- if (value != null) {
- value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
- }
- } else {
- value = metaObject == null ? null :metaObject.getValue(propertyName);
- }
- TypeHandler typeHandler = parameterMapping.getTypeHandler();
- if (typeHandler == null) {
- thrownew ExecutorException("Therewas no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
- }
- typeHandler.setParameter(ps, i + 1, value,parameterMapping.getJdbcType());
- }
-
- }
-
- }
- }
這裏面最重要的一句其實就是最後一句代碼,它的做用是用合適的TypeHandler完成參數的設置。那麼什麼是合適的TypeHandler呢,它又是如何決斷出來的呢?BaseStatementHandler的構造方法裏有這麼一句:
this.boundSql= mappedStatement.getBoundSql(parameterObject);
它觸發了sql 的解析,在解析sql的過程當中,TypeHandler也被決斷出來了,決斷的原則就是根據參數的類型和參數對應的JDBC類型決定使用哪一個TypeHandler。好比:參數類型是String的話就用StringTypeHandler,參數類型是整數的話就用IntegerTypeHandler等。
參數設置完畢後,執行數據庫操做(update或query)。若是是query最後還有個查詢結果的處理過程。
結果處理
結果處理使用ResultSetHandler來完成,默認的ResultSetHandler是FastResultSetHandler,它在建立StatementHandler時一塊兒建立,代碼以下:
- publicResultSetHandler newResultSetHandler(Executor executor, MappedStatementmappedStatement,
- RowBoundsrowBounds, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSqlboundSql) {
- ResultSetHandler resultSetHandler =mappedStatement.hasNestedResultMaps() ? newNestedResultSetHandler(executor, mappedStatement, parameterHandler,resultHandler, boundSql, rowBounds): new FastResultSetHandler(executor,mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
- resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
- returnresultSetHandler;
- }
能夠看出ResultSetHandler也是能夠被攔截的,能夠編寫本身的攔截器改變ResultSetHandler的默認行爲。
- ResultSetHandler內部一條記錄一條記錄的處理,在處理每條記錄的每一列時會調用TypeHandler轉換結果,以下:
-
- protectedbooleanapplyAutomaticMappings(ResultSet rs, List<String> unmappedColumnNames,MetaObject metaObject) throws SQLException {
- booleanfoundValues = false;
- for (StringcolumnName : unmappedColumnNames) {
- final Stringproperty = metaObject.findProperty(columnName);
- if (property!= null) {
- final ClasspropertyType =metaObject.getSetterType(property);
- if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
- final TypeHandler typeHandler = typeHandlerRegistry.getTypeHandler(propertyType);
- final Object value = typeHandler.getResult(rs,columnName);
- if (value != null) {
- metaObject.setValue(property, value);
- foundValues = true;
- }
- }
- }
- }
- returnfoundValues;
- }
從代碼裏能夠看到,決斷TypeHandler使用的是結果參數的屬性類型。所以咱們在定義做爲結果的對象的屬性時必定要考慮與數據庫字段類型的兼容性。