mybatis中mapper的代理过程

  在mapper的加载过程中我们讲到了,configuration文件最终会把mapper.xml配置文件解析成一个一个的MappedStatement.在MappedStatement中封装了组装成一个完成sql的所有条件,MappedStatement可以根据用户的查询条件生成真正的sql语句.在这片文章中我们讲详细的讲解一下Mybatis是怎么根据我们的配置生成我们使用的各种mapper类的.

  我们在调用SqlSession的getMapper(Calss)方法或者对应的mapper的时候,DefaultSqlSession会调用Configuration的getMapper方法,从configuration中查找/生成对应的代理.而configuration又会调用MapperRegistry的getMapper方法

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

  在MapperRegistry的getMapper方法中,会创建一个MapperProxyFactory实例,然后调用MapperProxyFactory的newInstance方法生成具体的代理.

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

  MapperProxyFactory.newInstance方法中会创建一个继承自InvocationHandler的MapperProxy类的实例.然后调用Proxy.newProxyInstance生成代理类.

  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
View Code

  根据jdk的动态代理原理,所有的真正代理的逻辑都在MapperProxy的invoke方法中.在invocke方法中会根据当前方法进行判断,如果是object或者default方法则会直接调用,不走代理,如果是普通方法则会创建一个MapperMethod,里面封装了当前调用的Method和当前类的class.最终所有的方法都会调用MapperMethod的execute方法.在execute方法中会根据当前方法的MapperStatement组装成具体的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;
  }
View Code

 

posted on 2022-08-24 23:41  monkeydai  阅读(172)  评论(0编辑  收藏  举报

导航