1首先我们从常见的开发入手,通常我们都是把namespace和接口进行绑定,所以重点就在下面这个方法;
XMLMapperBuilder 的buildStatementFromContext 方法如图;
跟踪代码
this.mappedStatements.put(ms.getId(), ms);
最后代码:
protected final Map<String, MappedStatement> mappedStatements; 这个是configuration一个属性
此时map为<namespace.方法名 MappedStatement对象>;
结论;
XMLMapperBuilder →buildStatementFromContext 追踪代码;
MapperBuilderAssistant → this.configuration.addMappedStatement(statement); → this.mappedStatements.put(ms.getId(), ms);
protected final Map<String, MappedStatement> mappedStatements;
此时map为<namespace.方法名 MappedStatement对象>
然后启动项目debug 代码可以看出dao层方法进入如下图;
项目启动是加入缓存
查询执行方法;
动态代理
结论;
方法调用过程(使用动态代理)
MapperRegistry→getMapper得到 MapperProxyFactory →
Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy)得到对应接口的代理对象
;也就创建是对应dao接口的实现类MapperProxy 泛型增加了代码的通用性;
MapperProxy调用invoke方法 反射拿到对应的method,通过 private final Map<Method, MapperMethod> methodCache 缓存拿到对应的MapperMethod对象,
methodCache缓存是初始化时候加载的;然后执行mapperMethod.execute,最后执行
MappedStatement ms = this.configuration.getMappedStatement(statement);statement=反射接口名字+方法名和xml对应,得到MappedStatement对象xml方法
List result = this.executor.query(ms, this.wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);