MyBatis源码笔记(四) -- mapper动态代理

相关参考文章:
MyBatis源码笔记(一) – 大致流程
MyBatis源码笔记(三) – mapper解析流程

DefaultSqlSession中有个getMapper方法,是获取指定类型的代理类

public <T> T getMapper(Class<T> type) {
 	return configuration.<T>getMapper(type, this);
 }

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
 	return mapperRegistry.getMapper(type, sqlSession);
}

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);
  }
}

可以看到是从configuration中的MapperRegistry成员中的knownMappers里取出相应的MapperProxyFactory,然后调用其newInstance方法进行实例化一个代理类。

public class MapperProxyFactory<T> {
public MapperProxyFactory(Class<T> mapperInterface) {
   	this.mapperInterface = mapperInterface;
 	}
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);
 	}
}

在解析mapper的时候,会把接口类型传进MapperProxyFactory的构造方法,然后上面调用newInstance(SqlSession sqlSession)方法时,就会创建一个MapperProxy对象,最后调用newInstance(MapperProxy mapperProxy)方法使用JDK代理实例化一个代理类。

代理类实际就是MapperProxy

public class MapperProxy<T> implements InvocationHandler, Serializable {
  ...
  private final SqlSession sqlSession;
  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 {
    //代理以后,所有Mapper的方法调用时,都会调用这个invoke方法
    //并不是任何一个方法都需要执行调用代理对象进行执行,如果这个方法是Object中通用的方法(toString、hashCode等)无需执行
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    //这里优化了,去缓存中找MapperMethod
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //执行
    return mapperMethod.execute(sqlSession, args);
  }

  //去缓存中找MapperMethod
  private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      //找不到才去new
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }
}

MapperProxy实现了InvocationHandler,所以主要逻辑在invoke里。上面可以看到,但需要代理方法时,会把方法封装成MapperMethod进行执行。

public class MapperMethod {

  private final SqlCommand command;
  private final MethodSignature method;

  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
	//SqlCommand封装了SQL命令,是静态内部类
    this.command = new SqlCommand(config, mapperInterface, method);
	//方法签名,静态内部类,封装了方法的返回值,参数等信息
    this.method = new MethodSignature(config, method);
  }

  //执行
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //可以看到执行时就是4种情况,insert|update|delete|select,分别调用SqlSession的4大类方法
    if (SqlCommandType.INSERT == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
      if (method.returnsVoid() && method.hasResultHandler()) {
        //如果有结果处理器
        executeWithResultHandler(sqlSession, args);
        result = null;
      } else if (method.returnsMany()) {
        //如果结果有多条记录
        result = executeForMany(sqlSession, args);
      } else if (method.returnsMap()) {
        //如果结果是map
        result = executeForMap(sqlSession, args);
      } else {
        //否则就是一条记录
        Object param = method.convertArgsToSqlCommandParam(args);
        result = sqlSession.selectOne(command.getName(), param);
      }
    } else {
      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;
  }
	...
}

execute方法逻辑很清晰,就是按不同的sql类型进行不同的处理,INSERT、UPDATE、DELETE只要返回影响的行数就行,而SELECT则要考虑返回值进行不同处理,最后把处理好的结果返回。

猜你喜欢

转载自blog.csdn.net/seasonLai/article/details/82854826