MyBatis之Mapper的动态代理实现原理

为了方便理解MyBatis的Mapper的动态代理实现原理,下面编写简单的动态代理实现方式,模仿MyBatis的Mapper实现一个UserMapper,通过定义Mapper接口 UserMapper,然后调用

UserMapper userMapper = MapperFactory.getMapper(UserMapper.class);

List list = userMapper.getList();

获取UserMapper的代理对象,代理对象直接返回一个List,但如果要有多个函数调用,需要根据不同的函数,进行不同的逻辑处理。仅仅做最简单的模拟,方便理解原理。

 

步骤:

 1. 定义Mapper文件,UserMapper

package org.ziegler.javabase.learnProxy;

import java.util.List;

public interface UserMapper {
    List getList();
}

2. 代理类实现MyMapperProxy,对应“MapperProxyFactory”

package org.ziegler.javabase.learnProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class MyMapperProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        List list = List.of(1, 3, 5);
        return list;
    }
}

3. Mapper工厂实现,对应“SqlSession”

package org.ziegler.javabase.learnProxy;

import java.lang.reflect.Proxy;

public class MapperFactory {

    public static  T getMapper(Class type) {
        MyMapperProxy myMapperProxy = new MyMapperProxy();

        return (T) Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                new Class[]{type},
                myMapperProxy);
    }

}

4. 调用测试,对应“sqlSession.getMapper(UserMapper.class)”

package org.ziegler.javabase.learnProxy;

import java.util.List;

import org.junit.jupiter.api.Test;

public class TestProxy {

    @Test
    void testGetMapper() {
        UserMapper userMapper = MapperFactory.getMapper(UserMapper.class);

        List list = userMapper.getList();
        System.out.println("list = " + list);
    }

}

输出:

list = [1, 3, 5]

 

你可能感兴趣的:(Java,MyBatis)