在使用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工程