源码讲解 —— 接口代理

话不多说,直接上图:

其实无论哪种方式,我们最终是需要找到对应的 SQL 语句,接口代理的方式就是通过 【包名.方法名】 的方式,去找到 xxxMapper.xml 文件中的 SQL 语句。

很明显,通过动态代理的方式,我们能够实现该功能。

创建接口

public interface PersonMapper {

    Person selectPersonById(Long pid);
}

创建接口代理类

import org.apache.ibatis.session.SqlSession;

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

public class MapperProxyHandler implements InvocationHandler {
    private SqlSession sqlSession;
    private Class<?> targetInterface;

    public MapperProxyHandler(SqlSession sqlSession,Class<?> targetInterface){
        this.sqlSession = sqlSession;
        this.targetInterface = targetInterface;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String className = targetInterface.getName();
        String methodName = method.getName();
        String statement = className + "." + methodName;

        return sqlSession.selectOne(statement,args[0]);
    }
}

创建代理工厂类

import java.lang.reflect.Proxy;

public class MapperProxyFactory {
    private Class<?> targetInterface;

    public MapperProxyFactory(Class<?> targetInterface){
        this.targetInterface = targetInterface;
    }

    public Object newInstance(MapperProxyHandler handler){
        return Proxy.newProxyInstance(targetInterface.getClassLoader(),
                new Class[]{targetInterface},
                handler);
    }
}

创建测试类

public class MapperProxyTest {

    public static void main(String[] args) {
        // 1、获取目标接口对象
        Class<?> targetInterface = PersonMapper.class;
        // 2、获取 SqlSession 对象
        SqlSession sqlSession = getSqlSession();
        MapperProxyHandler proxyHandler = new MapperProxyHandler(sqlSession,targetInterface);
        MapperProxyFactory mapperProxyFactory = new MapperProxyFactory(PersonMapper.class);
        PersonMapper personMapper = (PersonMapper)mapperProxyFactory.newInstance(proxyHandler);
        Person person = personMapper.selectPersonById(1L);
        System.out.println(person);
    }



    public static SqlSession getSqlSession() {
        //定义mybatis全局配置文件
        String resource = "mybatis-config.xml";
        //加载 mybatis 全局配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return  sessionFactory.openSession();
    }
}

总结

其实 Mybatis 内部实现方式大体上和上面差不多,在加入一些类型处理器,其实就是一个简易版本的 Mybatis

 

参考:

 

posted @   残城碎梦  阅读(184)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示