栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Mysql篇】mybatis通过jdk动态代理的原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Mysql篇】mybatis通过jdk动态代理的原理

mybatis通过jdk动态代理的原理

关键字:MapperRegistry .getMapper、mapperProxyFactory.newInstance、MapperProxy、InvocationHandler

使用Configuration的getMapper方法时,会调用mapperRegistry.getMapper方法,

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

    public MapperRegistry(Configuration config) {
        this.config = config;
    }

	// 看这里!
    public  T getMapper(Class type, SqlSession sqlSession) {
        MapperProxyFactory mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
            	// 看这里!
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }

而该方法又会调用**mapperProxyFactory.newInstance(sqlSession)**来生成一个具体的代理,

public class MapperProxyFactory {
	...

	// 这个是自己用用的哈
    protected T newInstance(MapperProxy mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }
	
	// 这个实例方法才是对外的,返回是一个泛型,生成具体的MapperProxy的
    public T newInstance(SqlSession sqlSession) {
        MapperProxy mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }
}

该MapperProxy类实现了InvocationHandler接口,并且实现了该接口的invoke方法,完成后续的一系列sql操作,并返回映射后的Java类

public class MapperProxy implements InvocationHandler, Serializable {
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            }

            if (this.isDefaultMethod(method)) {
                return this.invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable var5) {
            throw ExceptionUtil.unwrapThrowable(var5);
        }

        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        return mapperMethod.execute(this.sqlSession, args);
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/755716.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号