mybatis--动态代理实现

如果我们要使用MyBatis进行数据库操作的话,大致要做两件事情:

  1. 定义dao接口文件
    在dao接口中定义需要进行的数据库操作方法。
  2. 创建映射文件
    当有了dao接口后,还需要为该接口创建映射文件。映射文件中定义了一系列SQL语句,这些SQL语句和dao接口一一对应。

MyBatis在初始化的时候会将映射文件与dao接口一一对应,并根据映射文件的内容为每个函数创建相应的数据库操作能力。而我们作为MyBatis使用者,只需将dao接口注入给Service层使用即可。
那么MyBatis是如何根据映射文件为每个dao接口创建具体实现的?答案是——动态代理。

1、解析mapper文件

启动时加载解析mapper的xml

如果不是集成spring的,会去读取<mappers>节点,去加载mapper的xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="2"/>
    </settings>
    <typeAliases>
        <typeAlias alias="CommentInfo" type="com.xixicat.domain.CommentInfo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/demo"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/xixicat/dao/CommentMapper.xml"/>
    </mappers>
</configuration>

如果是集成spring的,会去读spring的sqlSessionFactory的xml配置中的mapperLocations,然后去解析mapper的xml

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置mybatis配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="com.xixicat.domain"/>
        <!-- 配置扫描Mapper XML的位置 -->
        <property name="mapperLocations" value="classpath:com/xixicat/dao/*.xml"/>
    </bean>

mapper节点解析过程

XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();

由上述代码可知,解析mapper节点的解析是由XMLMapperBuilder类的parse()函数来完成的,下面我们就详细看一下parse()函数。

public void parse() {
    // 若当前Mapper.xml尚未加载,则加载
    if (!configuration.isResourceLoaded(resource)) { 
      // 解析<mapper>节点
      configurationElement(parser.evalNode("/mapper"));
      // 将当前Mapper.xml标注为『已加载』(下回就不用再加载了)
      configuration.addLoadedResource(resource);
      // 【关键】将Mapper Class添加至Configuration中
      bindMapperForNamespace(); //绑定namespace
    }

    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
  }

这个函数主要做了两件事:

  1. 解析<mapper>节点,并将解析结果注册进configuration中;
  2. 将当前映射文件所对应的DAO接口的Class对象注册进configuration
    这一步极为关键!是为了给DAO接口创建代理对象,下文会详细介绍。

下面再进入bindMapperForNamespace()函数,看一看它做了什么:

private void bindMapperForNamespace() {
    // 获取当前映射文件对应的DAO接口的全限定名
    String namespace = builderAssistant.getCurrentNamespace();
    if (namespace != null) {
      // 将全限定名解析成Class对象
      Class<?> boundType = null;
      try {
        boundType = Resources.classForName(namespace);
      } catch (ClassNotFoundException e) {
      }
      if (boundType != null) {
        if (!configuration.hasMapper(boundType)) {
          // 将当前Mapper.xml标注为『已加载』(下回就不用再加载了)
          configuration.addLoadedResource("namespace:" + namespace);
          // 将DAO接口的Class对象注册进configuration中
          configuration.addMapper(boundType);
        }
      }
    }
  }

这个函数主要做了两件事:

  1. <mapper>节点上定义的namespace属性(即:当前映射文件所对应的DAO接口的权限定名)解析成Class对象
  2. 将该Class对象存储在configuration对象里的属性MapperRegistry中,见下代码
MapperRegistry mapperRegistry = new MapperRegistry(this)

public <T> void addMapper(Class<T> type) {
        this.mapperRegistry.addMapper(type);
    }

我们继续进入MapperRegistry

public class MapperRegistry {
  private final Configuration config;
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
}

MapperRegistry有且仅有两个属性:ConfigurationknownMappers
其中,knownMappers的类型为Map<Class<?>, MapperProxyFactory<?>>,它是一个Map,key为dao接口的class对象,而value为该dao接口代理对象的工厂。那么这个代理对象工厂是什么,又怎么产生的呢?我们先来看一下MapperRegistryaddMapper()函数。

  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 {
        // 创建MapperProxyFactory对象,并put进knownMappers中
        knownMappers.put(type, new MapperProxyFactory<T>(type));
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }

从这个函数可知,MapperProxyFactory是在这里创建,并put进knownMappers中的。
下面我们就来看一下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);
  }
}

这个类有三个重要成员:

  1. mapperInterface属性
    这个属性就是DAO接口的Class对象,当创建MapperProxyFactory对象的时候需要传入
  2. methodCache属性
    这个属性用于存储当前DAO接口中所有的方法。
  3. newInstance函数
    这个函数用于创建DAO接口的代理对象,它需要传入一个MapperProxy对象作为参数。而MapperProxy类实现了InvocationHandler接口,由此可知它是动态代理中的处理类,所有对目标函数的调用请求都会先被这个处理类截获,所以可以在这个处理类中添加目标函数调用前、调用后的逻辑。

2、DAO函数调用过程

当MyBatis初始化完毕后,configuration对象中存储了所有DAO接口的Class对象和相应的MapperProxyFactory对象(用于创建DAO接口的代理对象)。接下来,就到了使用DAO接口中函数的阶段了。
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
    List<Product> productList = productMapper.selectProductList();
    for (Product product : productList) {
        System.out.printf(product.toString());
    }
} finally {
    sqlSession.close();
}

我们首先需要从sqlSessionFactory对象中创建一个SqlSession对象,然后调用sqlSession.getMapper(ProductMapper.class)来获取代理对象。
我们先来看一下sqlSession.getMapper()是如何创建代理对象的?

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

sqlSession.getMapper()调用了configuration.getMapper(),那我们再看一下configuration.getMapper()

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

configuration.getMapper()又调用了mapperRegistry.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);
    }
  }

看到这里我们就恍然大悟了,原来它根据上游传递进来DAO接口的Class对象,从configuration中取出了该DAO接口对应的代理对象生成工厂:MapperProxyFactory
在有了这个工厂后,再通过newInstance函数创建该DAO接口的代理对象,并返回给上游。

OK,此时我们已经获取了代理对象,接下来就可以使用这个代理对象调用相应的函数了。

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
    List<Product> productList = productMapper.selectProductList();
} finally {
    sqlSession.close();
}

以上述代码为例,当我们获取到ProductMapper的代理对象后,我们调用了它的selectProductList()函数。

3、下面我们就来分析下代理函数调用过程。

当调用了代理对象的某一个代理函数后,这个调用请求首先会被发送给代理对象处理类MapperProxyinvoke()函数,这个类继承了InvocationHandler:

//这里会拦截Mapper接口的所有方法 
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (Object.class.equals(method.getDeclaringClass())) { //如果是Object中定义的方法,直接执行。如toString(),hashCode()等
      try {
        return method.invoke(this, args);//
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);  //其他Mapper接口定义的方法交由mapperMethod来执行
    return mapperMethod.execute(sqlSession, args);
  }

这个方法中,首先会过滤object中的通用方法,遇到object方法会直接执行;

但是如果是非通用方法,现执行cachedMapperMethod(method):从当前代理对象处理类MapperProxymethodCache属性中获取method方法的详细信息(即:MapperMethod对象)。如果methodCache中没有就创建并加进去。

有了MapperMethod对象后执行它的execute()方法,该方法就会调用JDBC执行相应的SQL语句,并将结果返回给上游调用者。至此,代理对象函数的调用过程结束!

MapperMethod类是统管所有和数据库打交道的方法。所以,不管你的dao层有多少方法,归结起来的sql语句都有且仅有只有insert、delete、update、select,可以预料在MapperMethod的execute方法中首先判断是何种sql语句。

 1   /**
 2    * 这个方法是对SqlSession的包装,对应insert、delete、update、select四种操作
 3    */
 4 public Object execute(SqlSession sqlSession, Object[] args) {
 5     Object result;//返回结果
 6    //INSERT操作
 7     if (SqlCommandType.INSERT == command.getType()) {
 8       Object param = method.convertArgsToSqlCommandParam(args);
 9       //调用sqlSession的insert方法 
10       result = rowCountResult(sqlSession.insert(command.getName(), param));
11     } else if (SqlCommandType.UPDATE == command.getType()) {
12       //UPDATE操作 同上
13       Object param = method.convertArgsToSqlCommandParam(args);
14       result = rowCountResult(sqlSession.update(command.getName(), param));
15     } else if (SqlCommandType.DELETE == command.getType()) {
16       //DELETE操作 同上
17       Object param = method.convertArgsToSqlCommandParam(args);
18       result = rowCountResult(sqlSession.delete(command.getName(), param));
19     } else if (SqlCommandType.SELECT == command.getType()) {
20       //如果返回void 并且参数有resultHandler  ,则调用 void select(String statement, Object parameter, ResultHandler handler);方法  
21       if (method.returnsVoid() && method.hasResultHandler()) {
22         executeWithResultHandler(sqlSession, args);
23         result = null;
24       } else if (method.returnsMany()) {
25         //如果返回多行结果,executeForMany这个方法调用 <E> List<E> selectList(String statement, Object parameter);   
26         result = executeForMany(sqlSession, args);
27       } else if (method.returnsMap()) {
28         //如果返回类型是MAP 则调用executeForMap方法 
29         result = executeForMap(sqlSession, args);
30       } else {
31         //否则就是查询单个对象
32         Object param = method.convertArgsToSqlCommandParam(args);
33         result = sqlSession.selectOne(command.getName(), param);
34       }
35     } else {
36         //接口方法没有和sql命令绑定
37         throw new BindingException("Unknown execution method for: " + command.getName());
38     }
39     //如果返回值为空 并且方法返回值类型是基础类型 并且不是void 则抛出异常  
40     if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
41       throw new BindingException("Mapper method '" + command.getName() 
42           + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
43     }
44     return result;
45   }

我们选取第26行中的executeForMany中的方法来解读试试看。

 1 private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
 2     List<E> result;
 3     Object param = method.convertArgsToSqlCommandParam(args);
 4     if (method.hasRowBounds()) { //是否分页查询,RowBounds中有两个数字,offset和limit
 5       RowBounds rowBounds = method.extractRowBounds(args);
 6       result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
 7     } else {
 8       result = sqlSession.<E>selectList(command.getName(), param);
 9     }
10     // issue #510 Collections & arrays support
11     if (!method.getReturnType().isAssignableFrom(result.getClass())) {
12       if (method.getReturnType().isArray()) {
13         return convertToArray(result);
14       } else {
15         return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
16       }
17     }
18     return result;
19   }

第6行和第8行代码就是我们真正执行sql语句的地方,原来兜兜转转它又回到了sqlSession的方法中。DefaultSqlSession是SqlSession的实现类,所以我们重点关注DefaultSqlSession类。

  public <E> List<E> selectList(String statement) {
    return this.selectList(statement, null);
  }

  public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }

  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
      return result;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

我们看到关于selectList有三个重载方法,最后调用的都是public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds)。在此方法中第一个参数为String类型且命名为statement,第二个参数为Object命名为parameter,回到MapperMethod的executeForMany方法,可以看到传递了什么参数进来,跟踪command.getName()是怎么来的。

private final SqlCommand command;

看来是一个叫做SqlCommand的变量,进而我们可以发现这个SqlCommand是MapperMethod的静态内部类。

 1 //org.apache.ibatis.binding.MapperMethod
 2   public static class SqlCommand {
 3 
 4     private final String name;
 5     private final SqlCommandType type;
 6 
 7     public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
 8       String statementName = mapperInterface.getName() + "." + method.getName();  //获取接口+方法名
 9       MappedStatement ms = null;  //定义一个MappedStatement,这个MapperedStatement稍后介绍
10       if (configuration.hasStatement(statementName)) {  //从Configuration对象查找是否有这个方法的全限定名称
11         ms = configuration.getMappedStatement(statementName);  //有,则根据方法的全限定名称获取MappedStatement实例
12       } else if (!mapperInterface.equals(method.getDeclaringClass())) { //如果没有在Configuration对象中找到这个方法,则向上父类中获取全限定方法名
13         String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
14         if (configuration.hasStatement(parentStatementName)) {  //在向上的父类查找是否有这个全限定方法名
15           ms = configuration.getMappedStatement(parentStatementName);   //有,则根据方法的全限定名称获取MappedStatement实例
16         }
17       }
18       if (ms == null) {
19         if(method.getAnnotation(Flush.class) != null){
20           name = null;
21           type = SqlCommandType.FLUSH;
22         } else {
23           throw new BindingException("Invalid bound statement (not found): " + statementName);
24         }
25       } else {
26         name = ms.getId();  //这个ms.getId,其实就是我们在mapper.xml配置文件中配置一条sql语句时开头的<select id="……"……,即是接口的该方法名全限定名称
27         type = ms.getSqlCommandType();  //显然这是将sql是何种类型(insert、update、delete、select)赋给type
28         if (type == SqlCommandType.UNKNOWN) {
29           throw new BindingException("Unknown execution method for: " + name);
30         }
31       }
32     }
33 
34     public String getName() {
35       return name;
36     }
37 
38     public SqlCommandType getType() {
39       return type;
40     }
41   }

  大致对MapperMethod的解读到此,再次回到DefaultSqlSession中,走到核心的这句

MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);

在获取到MappedStatement后,碰到了第一个SqlSession下的四大对象之一:Executor执行器。关于executor我们在下一篇文章中解析。

 
转载链接:https://www.jianshu.com/p/46c6e56d9774
https://www.cnblogs.com/yulinfeng/p/6076052.html

posted @ 2019-01-27 17:39  清晨_  阅读(7694)  评论(0编辑  收藏  举报