Mybatis源码阅读笔记(二)Mapper代理的获取与执行过程

201 阅读3分钟

mybatis中用户只需要提供Mapper接口,具体产生对象的工作交由mybatis代为完成,用户可以获取到相应的代理对象

代理获取

public void run(){
        //获取session
        SqlSession session=sqlSessionFactory.openSession();
        //获取StudentMapper代理对象
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        Student student = studentMapper.selectByPrimaryKey(1);
    }

进入session.getMapper()

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

继续进入函数,mapperRegister为configuration中一个重要组件,里面存放着Mapper接口的动态代理对象工厂,在创建MapperProxyFactory时使用了泛型,即为每个Mapper创建相应的代理工厂

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

        //获取代理对象工厂
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        //为 null时表示配置文件中没有配置该Mapper接口
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
            //由代理对象工厂创建实例对象
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }

mapperProxyFactory.newInstance()最终调用JDK自带的方法产生一个Mapper的代理对象

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

执行过程(以调用selectByPrimaryKey()为例)

首先进入代理类

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //并非所有方法都调用其代理执行,如果当前方法为Object中的方法,则直接执行
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      //这里invokeDefaultMethod()内部通过反射创建了新的对象,并执行了其对应的方法,但是不太理解它的作用和使用场景
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
     //获取MapperMethod, 如果缓存中有就直接获取,没有就先创建在放入缓存中
    final MapperMethod mapperMethod = cachedMapperMethod(method);
     //方法执行
    return mapperMethod.execute(sqlSession, args);
  }

MapperMethod包含两个属性,SQLCommand中包含了Mapper文件中定义的SQL语句信息,MethodSignature即方法签名,但其中也包含了方法的返回信息

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }

方法执行,这里对应的即为SELECT语句

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 {
          //selectByPrimaryKey() 将执行至此
          //首先将参数转换成对应的格式
          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;
  }

selectOne与executeForMany最终都会调用selectList()。executor.query()执行sql语句并返回结构,至此查询流程结束。

@Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      //执行相应的查询操作
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

在executor.query()执行会前先执行配置的拦截器,例如我在demo中使用了一个分页插件(pagehelper),它就是在这个时间点起作用,将会重新设置quert()的参数值。
分页插件在配置文件中的配置如下

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="pageSizeZero" value="true"/>
        </plugin>
</plugins>