MyBatis的Mapper机制

160 阅读4分钟

Mapper机制从流程上分为3个步骤

1.启动时做初始化动作

2.运行时使用getMapper方法生成动态代理

3.调用sql执行过程

Mapper机制初始化

系统启动首先会初始化Configuration,我们从Configuration的初始化位置开始看。请先找到XMLConfigBuilder类。

public Configuration parse() {
  if (parsed) {
    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  }
  parsed = true;
  parseConfiguration(parser.evalNode("/configuration"));
  return configuration;
}

这段方法,是xml解析过程。重点关注parseConfiguration

private void parseConfiguration(XNode root) {
  try {
    // 此处省略部分代码
    mapperElement(root.evalNode("mappers"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  }
}

继续跟进mapperElement

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        		// 此处省略部分代码
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

继续跟进configuration.addMapper(mapperInterface);一路可以跟进到MapperRegistry

public void addMappers(String packageName) {
  addMappers(packageName, Object.class);
}

这个方法是要加载某个包下面的所有xxxMapper.java(也就是我们所写的比如UserMapper.java,这种DAO行为接口),为后续运行时生成动态代理类做准备。(我们在业务代码中常写的sqlSession.getMapper方法,就是在生成动态代理)

public class MapperRegistry {
  
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
  
	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<Mapper接口类型, Mapper代理的工场对象>
        // 初始化时,会把这些东西缓存起来。为后续生成动态代理做准备。
        knownMappers.put(type, new MapperProxyFactory<T>(type));
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }
}

关注下knownMappers,这里面的keyvalue分别是<Mapper接口类型, Mapper代理的工场对象>

初始化时,会把这些东西缓存起来。为后续生成动态代理做准备。

使用getMapper方法生成动态代理

还是在MapperRegistry类中,调用getMapper方法生成动态代理类。关于动态代理不太熟悉的同学,可以相关设计模式,这个模式非常重要。

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

再来追踪下MapperProxyFactory,我把其中不太重要的部分去掉了

public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

  // 去掉了一些不太重要的部分代码
  
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    // 实际使用了JDK的动态代理,接口类型就是初始化时候放进knownMappers中的某一个。
    // 具体类型是在getMapper的时候传入的。
    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);
  }

}

实际使用了JDK的动态代理,接口类型就是初始化时候放进knownMappers中的某一个。具体类型是在getMapper的时候传入的。具体我们再回顾下上面那个MyBatis的调用案例。

MyBatis的示意代码

public Student findStudentById(int studentId) {
  SqlSession sqlSession = MyBatisUtil.getSqlSession();
  try {
    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    Student student = studentMapper.queryByPrimaryKey(studentId);
    return student;
  } finally {
    sqlSession.close();
  }
}

从这边可以看到。在调用getMapper时,会传入StudentMapper接口的类型。MyBatis会为这个接口生成动态代理类。下面我们看看这个动态代理实际执行了什么操作。找到MapperProxy类

public class MapperProxy<T> implements InvocationHandler, Serializable {

  private static final long serialVersionUID = -6424540398559729838L;
  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;
  }

  // 重点关注这个invoke方法
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 去掉了一些不太重要的部分代码
    final MapperMethod mapperMethod = cachedMapperMethod(method);// 这边先看看缓存
    return mapperMethod.execute(sqlSession, args);
  }
	// 去掉了一些不太重要的部分代码
}

在业务代码中调用任何一个sql方法,比如selectByPrimaryKey()都会来到这个invoke方法中。我们继续追踪mapperMethod.execute方法

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

看到上面这个方法,大家应该会明白了。到这边,所有的方法都会根据command.getType(),分化为insertupdatedeleteselect这4个元操作。

接下来的调用代码就不再这边继续分析了。感兴趣的同学可以继续更进。