MyBatis 学习记录2 Mapper对象是如何生成的

时间:2023-03-09 18:09:39
MyBatis 学习记录2 Mapper对象是如何生成的

主题

  以前我一直有一个问题不懂.并且觉得很神奇.就是Mybatis我们开发的时候只需要定义接口,并没有写实现类,为什么我们运行的时候就可以直接使用? 现在我想分享下这部分大致是怎么实现的.

在启动的时候

MyBatis 学习记录2 Mapper对象是如何生成的

根据之前的分享,在初始化阶段Build SqlSessionFactory的时候需要用到XMLConfigBuilder去parse XML文件生成Configuration对象,在 parse的步骤中其中有一步就是parse mappers节点

MyBatis 学习记录2 Mapper对象是如何生成的

MyBatis 学习记录2 Mapper对象是如何生成的

在parse mapper过程中会用到XMLMapperBuilder去parse.一步一步进入断点.

MyBatis 学习记录2 Mapper对象是如何生成的

会发现后面会调用configuration的addMapper方法.它会调用MapperRegistry的addMapper方法

MyBatis 学习记录2 Mapper对象是如何生成的

MapperRegistry相当用knownMappers这个hashmap于为每个Mapper注册一次,其中key是你自定义的Mapper接口的class,Value是MapperProxyFactory类的对象.

Factory一个就是一个工厂类,它肯定需要生产对应的对象,从名字上也能发现它生产的就是MapperProxy

 /**
* Copyright 2009-2015 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.binding; import org.apache.ibatis.session.SqlSession; import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; /**
* @author Lasse Voss
*/
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);
} }
 /**
* Copyright 2009-2015 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.binding; import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.SqlSession; import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map; /**
* @author Clinton Begin
* @author Eduardo Macarron
*/
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;
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
} private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
methodCache.put(method, mapperMethod);
}
return mapperMethod;
} }

从代码中我们可以得知,这里是用了JDK动态代理,MapperProxy类implements了InvocationHandler,

如果是调用自定义Mapper的Object类中的方法,比如toString,那就直接调用,否则的话调用mapperMethod.execute去执行对应的方法(比如selectById).那么mapperMethod是什么呢?

这个类的对象其实就是对应你写的Mapper里的方法,你的每个方法对应1个MapperMethod,相当于是Java的Method的包装.

另外还包含了你在XML里定义的SQL字符串, 是select还是insert还是update,delete操作等信息.相当于融合了你定义的Mapper里的Method和你为每个Method在XML里的写的信息.

这样你调用mapperMethod.execute的时候就能找到对应的SQL去执行了.

通过SqlSession获取Mapper

初始化完成后就如同之前的介绍,会在confuguration的mapperRegistry里注册好了各种MapperFactory.那么通过SqlSession去获取Mapper的时候也是类似的.会调用configuration去获取Mapper,内部会调用mapperRegistry去获取Mapper

MyBatis 学习记录2 Mapper对象是如何生成的

MyBatis 学习记录2 Mapper对象是如何生成的

然后通过MapperProxyFactory去创建一个MapperProxy并返还

MyBatis 学习记录2 Mapper对象是如何生成的

MyBatis 学习记录2 Mapper对象是如何生成的

小结

1.说白了,其实就是利用JDK动态代理,返回给你1个实现了你写的Mapper接口的对象,而其中的Invocation接口的实现类就是MapperProxy.

2.在初始化阶段会为你写的每个Mapper在Configuration的MapperRegistry里注册一个MapperFactory,当你要获取Mapper实例的时候就通过这个Factory来new.

3.当你调用Mapper.XXX方法的时候,比如select,就会调用MapperProxy的invoke方法,获取你定义在Mapper里的xxx方法对应的MapperMethod对象,这个对象就是Method的封装,同时在XML里找到对应的select语句再执行.

4.你写的每个Mapper类的对象对应1个MapperProxyFactory生成1个MapperProxy,你在Mapper中定义的每个方法对应1个MapperMethod,它是Java的Method的封装