mybatis之binding包之mapperInterface的原理

binding包下的核心类

MapperMethod

主要功能:把crud的方法委托给SqlSession.

MapperProxy

主要功能:mapperInterface的crud方法实际执行入口,把具体的功能委托给MapperMethod

MapperProxyFactory

主要功能:生成proxy代理

MapperRegistry

主要功能:getMapper,addMapper

我们平时使用mybatis的时候是用的一个接口,OrderMapper,这个orderMapper接口为什么能实现相关的功能呢?
原因就是mybatis会把这个接口生成一个动态代理类,我们去mybatis的binding包下面看看,就发现有个MapperProxy代理类,这个MapperProxy继承了InvocationHandler.
这个包下面的类的设计挺棒的.下面逻辑了核心的四个类.MapperProxy并没有直接的暴露出去,Mybatis封装了一个MapperRegistry,当getMapper被调用的时候,先获取MapperProxyFactory,因为虽然现在使用的是MapperProxy,如果后面的实现发生了变化呢?为了把这个变化点封装出来,Mybatis用了Factory模式.

 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 {
      //MapperRegistry -> MapperProxyFactory
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
  public T newInstance(SqlSession sqlSession) {
    //封装成MapperProxy MapperProxy实现了InvocationHandler
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    //remove redundant t
    return newInstance(mapperProxy);
  }

这里生成了mapper接口的代理类,用的的jdk的动态代理.

  protected T newInstance(MapperProxy<T> mapperProxy) {
    //用proxy生成代理对象.
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
  }

我们知道动态代理的核心调用是invoke方法,我们进入到这个invoke方法.这里的核心就是把事情委托给MapperMethod了.然后MapperMethod跟再下一层SqlSession进行交互的sql执行类进行交互.每一层代码都很清晰,每个类都有自己的清晰的职责.

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //
      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负责执行sql
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //switch case update or select .....
    return mapperMethod.execute(sqlSession, args);
  }

到这里,就一目了然了吧.这里做个简单的逻辑判断,然后就交给SqlSession,然后接受到SqlSession返回的结果.

 //最终执行sql的地方
  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()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
          //
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
          //
        } 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;
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。