在开始分析以前,先来了解一下这个模块中的核心组件之间的关系,如图:sql
MapperRegistry是Mapper接口及其对应的代理对象工程的注册中心,Configuration是Mybatis全局性的配置对象,在初始化的过程当中,全部配置信息会被解析成相应的对象并记录到Configuration对象中,这在以前也详细介绍了。Configuration.mapperRegistry字段记录当前使用的MapperRegistry对象,数组
public class MapperRegistry { // 全局惟一的配置对象,其中包含了全部的配置信息 private final Configuration config; // 记录Mapper接口与对应MapperProxyFactory之间的关系 private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>(); }
private void bindMapperForNamespace() { 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); configuration.addMapper(boundType); } } } }
public <T> void addMapper(Class<T> type) { mapperRegistry.addMapper(type); }
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 { knownMappers.put(type, new MapperProxyFactory<T>(type)); // 注解处理 MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse(); loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } } }
在须要执行SQL语句时,会先获取mapper借口的代理对象,例如:缓存
@Test public void findUserById() { SqlSession sqlSession = getSessionFactory().openSession(); UserDao userMapper = sqlSession.getMapper(UserDao.class); User user = userMapper.findUserById(1); Assert.assertNotNull("没找到数据", user); }
DefaultSqlSession类中方法以下,其实是经过JDK动态代理生成的代理对象app
public <T> T getMapper(Class<T> type) { return this.configuration.getMapper(type, this); }
Configuration类方法以下:ide
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); }
MapperRegistry类中方法以下:ui
@SuppressWarnings("unchecked") public <T> T getMapper(Class<T> type, SqlSession sqlSession) { //查找指定type对象的MapperProxyFactory对象 final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) {//若是为空抛出异常 throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { // 建立实现了type接口的代理对象 return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
MapperProxyFactory主要负责建立代理对象this
@SuppressWarnings("unchecked") protected T newInstance(MapperProxy<T> mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); } public T newInstance(SqlSession sqlSession) { final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); }
MapperProxy实现了InvocationHandler接口,对动态代理的能够先去了解这篇文章http://www.javashuo.com/article/p-aifratub-hk.htmlspa
public class MapperProxy<T> implements InvocationHandler, Serializable { private static final long serialVersionUID = -6424540398559729838L; // 记录关联的SQLSession对象 private final SqlSession sqlSession; // mapper接口对应的class对象 private final Class<T> mapperInterface; private final Map<Method, MapperMethod> methodCache; public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) { this.sqlSession = sqlSession; this.mapperInterface = mapperInterface; this.methodCache = methodCache; } @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 (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } // 从缓存中获取MapperMethod 对象,若是没有就建立新的并添加 final MapperMethod mapperMethod = cachedMapperMethod(method); // 执行sql 语句 return mapperMethod.execute(sqlSession, args); } }
MapperMethod中封装了Mapper接口中对应方法的信息,以及对应SQL语句的信息,.net
public class MapperMethod { // 记录SQL语句的名称和类型 private final SqlCommand command; // mapper接口中对应方法的相关信息 private final MethodSignature method; public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) { this.command = new SqlCommand(config, mapperInterface, method); this.method = new MethodSignature(config, mapperInterface, method); } public Object execute(SqlSession sqlSession, Object[] args) { Object result; 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: if (method.returnsVoid() && method.hasResultHandler()) { // 处理返回值为void ,ResultSet 经过ResultHand处理的方法 executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) { // 处理返回值为集合或者数组的方法 result = executeForMany(sqlSession, args); } else if (method.returnsMap()) { // 处理返回值为map的方法 result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { // 处理返回值为cursor的方法 result = executeForCursor(sqlSession, args); } else { // 处理返回值为单一对象的方法 Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); } 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; } }