在使用Mybatis的時候你們可能都有一個疑問,爲何只寫Mapper接口就能操做數據庫?java
它的主要實現思想是:使用動態代理生成實現類,而後配合xml的映射文件中的SQL語句來實現對數據庫的訪問。git
Mybatis是在iBatis上演變而來ORM框架,因此Mybatis最終會將代碼轉換成iBatis編程模型,而 Mybatis 代理階段主要是將面向接口編程模型,經過動態代理轉換成ibatis編程模型。github
咱們不直接使用iBatis編程模型的緣由是爲了解耦,從下面的兩種示例咱們能夠看出,iBatis編程模型和配置文件耦合很嚴重。spring
@Test // 面向接口編程模型 public void quickStart() throws Exception { // 2.獲取sqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { initH2dbMybatis(sqlSession); // 3.獲取對應mapper PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); JdkProxySourceClassUtil.writeClassToDisk(mapper.getClass().getSimpleName(), mapper.getClass()); // 4.執行查詢語句並返回結果 Person person = mapper.selectByPrimaryKey(1L); System.out.println(person.toString()); } }
@Test // ibatis編程模型 public void quickStartIBatis() throws Exception { // 2.獲取sqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { initH2dbMybatis(sqlSession); // ibatis編程模型(與配置文件耦合嚴重) Person person = sqlSession.selectOne("com.xiaolyuh.domain.mapper.PersonMapper.selectByPrimaryKey", 1L); System.out.println(person.toString()); } }
InvocationHandler
接口,經過該加強的invoke方法實現了對數據庫的訪問sqlSession
來完成了對數據庫的操做在Mybatis 源碼(二)中咱們會發現當配置文件解析完成的最後一步是調用org.apache.ibatis.builder.xml.XMLMapperBuilder#bindMapperForNamespace
方法。該方法的主要做用是:根據 namespace 屬性將Mapper接口的動態代理工廠(MapperProxyFactory)註冊到 MapperRegistry 中。源碼以下:sql
private void bindMapperForNamespace() { // 獲取namespace屬性(對應Mapper接口的全類名) String namespace = builderAssistant.getCurrentNamespace(); if (namespace != null) { Class<?> boundType = null; try { boundType = Resources.classForName(namespace); } catch (ClassNotFoundException e) { //ignore, bound type is not required } if (boundType != null) { // 防止重複加載 if (!configuration.hasMapper(boundType)) { // Spring may not know the real resource name so we set a flag // to prevent loading again this resource from the mapper interface // look at MapperAnnotationBuilder#loadXmlResource configuration.addLoadedResource("namespace:" + namespace); // 將Mapper接口的動態代理工廠註冊到 MapperRegistry 中 configuration.addMapper(boundType); } } } }
org.apache.ibatis.session.Configuration#addMapper
該方法直接回去調用org.apache.ibatis.binding.MapperRegistry#addMapper
方法完成註冊。數據庫
public <T> void addMapper(Class<T> type) { // 必須是接口 if (type.isInterface()) { if (hasMapper(type)) { // 防止重複註冊 throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { // 根據接口類,建立MapperProxyFactory代理工廠類 knownMappers.put(type, new MapperProxyFactory<>(type)); // It's important that the type is added before the parser is run // otherwise the binding may automatically be attempted by the // mapper parser. If the type is already known, it won't try. MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse(); loadCompleted = true; } finally { // 若是加載出現異常須要移除對應Mapper if (!loadCompleted) { knownMappers.remove(type); } } } }
BindingException
異常在Mybatis 源碼(一)的快速開始中有以下代碼,經過 sqlSession獲取Mapper的代理對象:apache
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
sqlSession.getMapper(PersonMapper.class)
最終調用的是org.apache.ibatis.binding.MapperRegistry#getMapper
方法,最後返回的是PersonMapper
接口的代理對象,源碼以下:編程
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { // 根據類型獲取對應的代理工廠 final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { // 根據工廠類新建一個代理對象,並返回 return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
每個Mapper接口對應一個MapperProxyFactory工廠類。 MapperProxyFactory經過JDK動態代理建立代理對象,Mapper接口的代理對象是方法級別,因此每次訪問數據庫都須要新建立代理對象。源碼以下:數組
protected T newInstance(MapperProxy<T> mapperProxy) { // 使用JDK動態代理生成代理實例 return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); } public T newInstance(SqlSession sqlSession) { // Mapper的加強器 final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); }
import com.sun.proxy..Proxy8; import com.xiaolyuh.domain.model.Person; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; public final class $Proxy8 extends Proxy implements Proxy8 { private static Method m3; ... public $Proxy8(InvocationHandler var1) throws { super(var1); } ... public final Person selectByPrimaryKey(Long var1) throws { try { return (Person)super.h.invoke(this, m3, new Object[]{var1}); } catch (RuntimeException | Error var3) { throw var3; } catch (Throwable var4) { throw new UndeclaredThrowableException(var4); } } static { try { m3 = Class.forName("com.sun.proxy.$Proxy8").getMethod("selectByPrimaryKey", Class.forName("java.lang.Long")); } catch (NoSuchMethodException var2) { throw new NoSuchMethodError(var2.getMessage()); } catch (ClassNotFoundException var3) { throw new NoClassDefFoundError(var3.getMessage()); } } }
從代理類的反編譯結果來看,都是直接調用加強器的invoke
方法,進而實現對數據庫的訪問。緩存
經過上訴反編譯代理對象,咱們能夠發現全部對數據庫的訪問都是在加強器org.apache.ibatis.binding.MapperProxy#invoke
中實現的。
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { // 若是是Object自己的方法不加強 if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } // 判斷是不是默認方法 else if (method.isDefault()) { if (privateLookupInMethod == null) { return invokeDefaultMethodJava8(proxy, method, args); } else { return invokeDefaultMethodJava9(proxy, method, args); } } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } // 從緩存中獲取MapperMethod對象 final MapperMethod mapperMethod = cachedMapperMethod(method); // 執行MapperMethod return mapperMethod.execute(sqlSession, args); }
MapperMethod
封裝了Mapper接口中對應方法的信息(MethodSignature),以及對應的sql語句的信息(SqlCommand);它是mapper接口與映射配置文件中sql語句的橋樑; MapperMethod對象不記錄任何狀態信息,因此它能夠在多個代理對象之間共享;
public Object execute(SqlSession sqlSession, Object[] args) { Object result; // 根據SQL類型,調用不一樣方法。 // 這裏咱們能夠看出,操做數據庫都是經過 sqlSession 來實現的 switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: // 根據方法返回值類型來確認調用sqlSession的哪一個方法 // 無返回值或者有結果處理器 if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; } // 返回值是否爲集合類型或數組 else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } // 返回值是否爲Map else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } // 返回值是否爲遊標類型 else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args); } // 查詢單條記錄 else { // 參數解析 Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); if (method.returnsOptional() && (result == null || !method.getReturnType().equals(result.getClass()))) { result = Optional.ofNullable(result); } } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; } private <E> Object executeForMany(SqlSession sqlSession, Object[] args) { List<E> result; // 將方法參數轉換成SqlCommand參數 Object param = method.convertArgsToSqlCommandParam(args); if (method.hasRowBounds()) { // 獲取分頁參數 RowBounds rowBounds = method.extractRowBounds(args); result = sqlSession.selectList(command.getName(), param, rowBounds); } else { result = sqlSession.selectList(command.getName(), param); } // issue #510 Collections & arrays support if (!method.getReturnType().isAssignableFrom(result.getClass())) { if (method.getReturnType().isArray()) { return convertToArray(result); } else { return convertToDeclaredCollection(sqlSession.getConfiguration(), result); } } return result; }
在execute
方法中完成了面向接口編程模型到iBatis編程模型的轉換,轉換過程以下:
MapperMethod.SqlCommand. type
+MapperMethod.MethodSignature.returnType
來肯定須要調用SqlSession
中的那個方法MapperMethod.SqlCommand. name
來找到須要執行方法的全類名MapperMethod.MethodSignature.paramNameResolver
來轉換須要傳遞的參數在Mybatis中SqlSession至關於一個門面,全部對數據庫的操做都須要經過SqlSession接口,SqlSession中定義了全部對數據庫的操做方法,如數據庫讀寫命令、獲取映射器、管理事務等,也是Mybatis中爲數很少的有註釋的類。
經過上面的源碼解析,能夠發現Mybatis面向接口編程是經過JDK動態代理模式來實現的。主要執行流程是:
MapperProxyFactory
註冊到MapperRegistry
sqlSession
經過MapperProxyFactory
獲取Mapper接口的代理類MapperProxy
調用XML映射文件中SQL節點的封裝類MapperMethod
MapperMethod
將Mybatis 面向接口的編程模型轉換成iBatis編程模型(SqlSession模型)SqlSession
完成對數據庫的操做https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases
spring-boot-student-mybatis工程