Mybatis中getMapper方法的作用及流程

   Mabtis作为一款优秀的持久层框架,不仅提高了我们的开发效率,同时也具备方便快捷的特点。通常我们配置MyBatis的时候都会配置一系列Mappers接口类到MyBatis中,但是如果我们不配置这些Mapper也是可以执行Mapper.xml文件中的SQL语句的,之所以要配置是因为直接使用接口会比不使用接口调用更方便,下面我们先看看不使用接口如何执行SQL。

    Mapper.xml 如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
<mapper namespace="org.mapper.UserMapper">
	<cache/>
    <select id="selectAll"  resultType="User">
        select * from tb_oder
    </select>
    <select id="selectByName"  resultType="User" parameterType="string"
    	useCache="false">
        select * from tb_oder where name like concat(#{keyWords},'%')
    </select>
    <update id="updateAge" parameterType="User" flushCache="true">
    	update tb_oder set age=#{age} where name =#{name}
    </update>
</mapper>

一些相关的配置就不赘述了,如果需要请查看之前的博客。现在需要调用该xml中的id为selectAll的语句, 我们只需要在获取到session后执行session.selectList(“selectAll”)语句即可。该方法执行的逻辑分为两步:第一步,根据selectAll去MyBatis的configuration中找到对应MappedStatement,然后调用执行器的query方法,并将上一步查询到的MappedStatement作为参数传入,最终将执行器的query方法的结果返回。补充:MappedStatement是在配置加载的时候存储在configuration中的一个Map中的,每个MappedStatement有一个Id,这个id就是mapper.xml中sql语句的id。如果mapper.xml配置namaspace的话,id会变为namaspace.sql语句的id。

@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();
    }
  }
接下来我们看看如何通过配置的mapper接口操作数据库呢?

1.获取指定的Mapper

DefaultSqlSession中的如下方法:
@Override
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
Configuration的getMapper如下:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
@SuppressWarnings("unchecked")
  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);
    }
  }

关键的地方就在最后的这个getMapper方法中。我们逐步分析:

1.knownMappers是什么?

它是MapperRegistry的一个final性质的私有类变量,指向一个HashMap的对象地址。
public class MapperRegistry {
 
  private final Configuration config;
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
 
  public MapperRegistry(Configuration config) {
    this.config = config;
  }
 
  @SuppressWarnings("unchecked")
  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);
    }
  }
  
  public <T> boolean hasMapper(Class<T> type) {
    return knownMappers.containsKey(type);
  }
 
  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.put(type, new MapperProxyFactory<T>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }
 
  /**
   * @since 3.2.2
   */
  public Collection<Class<?>> getMappers() {
    return Collections.unmodifiableCollection(knownMappers.keySet());
  }
 
  /**
   * @since 3.2.2
   */
  public void addMappers(String packageName, Class<?> superType) {
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
    for (Class<?> mapperClass : mapperSet) {
      addMapper(mapperClass);
    }
  }
 
  /**
   * @since 3.2.2
   */
  public void addMappers(String packageName) {
    addMappers(packageName, Object.class);
  }
  
}
  1. final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) knownMappers.get(type)

    该句是从knownMappers中获取到指定类型的mapperProxyFactory。那么MapperProxyFactory是什么呢?根据命名规范可以知道一个工程类,该工厂内是用来创建MapperProxy的。接下里我们看看MapperProxyFactory和MapperProxy以及MapperMethod。

2.1 MapperProxyFactory

public class MapperProxyFactory<T> {
 
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
 
  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
 
  public Class<T> getMapperInterface() {
    return mapperInterface;
  }
 
  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }
 
  @SuppressWarnings("unchecked")
  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);
  }
 
}

2.2 MapperProxy

接着上句继续分析:mapperProxyFactory.newInstance(sqlSession)。查看实现如下:

@SuppressWarnings("unchecked")
  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);
  }

首先生成一个MapperProxy,然后调用重载的newInstance方法生成一个代理对象。这是Mapper接口能够实现SQL执行的关键,基于JDK的动态代理机制。接着我们看MapperProxy的代码中,重写的invoke()方法,

@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 (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

该方法的实现中我们可以看到最后一行 mapperMethod.execute(sqlSession, args),查看实现后可以看到如下代码:

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

我们能够看到根据Method的不同类型去调用sqlSession中对应的方法,其后续执行逻辑和本文一开始讲的执行MappedStatement一样。至此,我们就已经知道Mapper接口是如何执行的了。还有一些Mybatis配置加载过程中将Mapper存储在knownMappers并同时生成一个MapperProxyFactory等就不做具体的分析。所以,如果不自己实现接口类,mybatis用动态代理帮我实现了实现类,然后再调用了相应的SqlSession方法。

总结

第一阶段:配置加载过程中为每个Mapper创建一个MapperProxyFactory;

第二阶段:获取Mapper实现类阶段为每个Mapper通过JDK的动态代理生成一个代理的实现类并返回MapperProxy;

第三阶段:调用代理类的方法。在MapperProxy的invoke方法中根据执行的接口方法名生成MapperMethod,如果有缓存则直接使用缓存的MapperMethod。然后调用MapperMethod的execute方法,该方法中会调用对应的session中的方法,进而找到对应的MappedStatement,然后使用执行器执行MappedStatement对应的sql。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

当使用dao实现类方式时

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 11
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值