Mybatis源码剖析 之 Mapper代理方式

回顾下写法:

public static void main(String[] args) {
    //前三步都相同
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = factory.openSession();
    //这⾥不再调⽤SqlSession的api,⽽是获得了接⼝对象,调⽤接⼝中的⽅法。
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.getUserByName("tom");
    }

思考一个问题,通常的Mapper接口我们都没有实现的方法却可以使用,是为什么呢?答案很简单动态代理。

        开始之前介绍一下MyBatis初始化时对接口的处理:MapperRegistry是Configuration中的一个属性,它内部维护一个HashMap用于存放mapper接口的工厂类,每个接口对应一个工厂类。

mappers中可以配置接口的包路径,或者某个具体的接口类。

<mappers>
        <mapper class="com.lagou.mapper.UserMapper"/>
        <package name="com.lagou.mapper"/>
</mappers>

        当解析mappers标签时,它会判断解析到的是mapper配置文件时,会再将对应配置文件中的增删 改查标签 封装成MappedStatement对象,存入mappedStatements中。(上文介绍了)当判断解析到接口时,会建此接口对应的MapperProxyFactory对象,存入HashMap中,key =接口的字节码对象,value =此接口对应的MapperProxyFactory对象。 

1、getmapper() 

进入 sqlSession.getMapper(UserMapper.class )中

    //DefaultSqlSession 中的 getMapper
    public <T> T getMapper(Class<T> type) {
        return configuration.<T>getMapper(type, this);
    }
    //configuration 中的给 g etMapper
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        return mapperRegistry.getMapper(type, sqlSession);
    }
    //MapperRegistry 中的 g etMapper
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//从 MapperRegistry 中的 HashMap 中拿 MapperProxyFactory
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
    //通过动态代理⼯⼚⽣成示例。
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }
    //MapperProxyFactory 类中的 newInstance ⽅法
    public T newInstance(SqlSession sqlSession) {
    //创建了 JDK动态代理的Handler类
        final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    //调⽤了重载⽅法
        return newInstance(mapperProxy);
    }
    //MapperProxy 类,实现了 InvocationHandler 接⼝
    public class MapperProxy<T> implements InvocationHandler, Serializable {
        //省略部分源码
        private final SqlSession sqlSession;
        private final Class<T> mapperInterface;
        private final Map<Method, MapperMethod> methodCache;
        //构造,传⼊了 SqlSession,说明每个session中的代理对象的不同的!
        public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
            this.sqlSession = sqlSession;
            this.mapperInterface = mapperInterface;
            this.methodCache = methodCache;
        }
//省略部分源码
    }

2、invoke()

        在动态代理返回了示例后,我们就可以直接调用mapper类中的方法了,但代理对象调用方法,执行是在MapperProxy中的invoke方法中

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            //如果是Object定义的⽅法,直接调⽤
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            } else if (isDefaultMethod(method)) {
                return invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
        }
        // 获得 MapperMethod 对象
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        //重点在这:MapperMethod最终调⽤了执⾏的⽅法
        return mapperMethod.execute(sqlSession, args);
    }

进入execute方法:

 public Object execute(SqlSession sqlSession, Object[] args) {
        Object result;
        //判断mapper中的⽅法类型,最终调⽤的还是SqlSession中的⽅法 switch
        (command.getType()) {
            case INSERT: {
                //转换参数
                Object param = method.convertArgsToSqlCommandParam(args);
                //执⾏INSERT操作
                // 转换 rowCount
                result = rowCountResult(sqlSession.insert(command.getName(), param));
                break;
            }
            case UPDATE: {
                //转换参数
                Object param = method.convertArgsToSqlCommandParam(args);
                // 转换 rowCount
                result = rowCountResult(sqlSession.update(command.getName(), param));
                break;
            }
            case DELETE: {
                //转换参数
                Object param = method.convertArgsToSqlCommandParam(args);
                // 转换 rowCount
                result = rowCountResult(sqlSession.delete(command.getName(), param));
                break;
            }
            case SELECT:
                //⽆返回,并且有ResultHandler⽅法参数,则将查询的结果,提交给 ResultHandler 进⾏处理
                if (method.returnsVoid() && method.hasResultHandler()) {
                    executeWithResultHandler(sqlSession, args);
                    result = null;
                    //执⾏查询,返回列表
                } else if (method.returnsMany()) {
                    result = executeForMany(sqlSession, args);
                    //执⾏查询,返回Map
                } else if (method.returnsMap()) {
                    result = executeForMap(sqlSession, args);
                    //执⾏查询,返回Cursor
                } else if (method.returnsCursor()) {
                    result = executeForCursor(sqlSession, args);
                    //执⾏查询,返回单个对象
                } else {
                    //转换参数
                    Object param = method.convertArgsToSqlCommandParam(args);
                    //查询单条
                    result = sqlSession.selectOne(command.getName(), param);
                    if (method.returnsOptional() &&
                            (result == null || !method.getReturnType().equals(result.getClass()))) {
                        result = Optional.ofNullable(result);
                    }
                }
                break;
            case FLUSH:
                result = sqlSession.flushStatements();
                break;
            default:
                throw new BindingException("Unknown execution method for: " + command.getName());
        }
        //返回结果为null,并且返回类型为基本类型,则抛出BindingException异常
        if(result ==null&&method.getReturnType().isPrimitive() &&!method.returnsVoid()){
            throw new BindingException("Mapper method '" + command.getName() + "attempted to return null from a method with a primitive return type(" + method.getReturnType() + "). ");
        }
        //返回结果
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
MyBatis是一个Java持久层框架,提供了灵活的SQL映射和便捷的数据库访问。Mapper接口是MyBatis中定义SQL映射的方式之一。下面是MyBatis Mapper码分析的一般步骤: 1. 首先,需要了解Mapper接口和XML映射文件之间的对应关系。在XML映射文件中定义了SQL语句和结果映射规则,而Mapper接口则提供了对应的方法。 2. 接下来,可以分析Mapper接口的实现类。MyBatis会动态生成Mapper接口的实现类,这些实现类会根据XML映射文件中定义的SQL语句进行具体的数据库操作。 3. 在实现类中,可以找到具体的数据库操作方法。这些方法会通过SqlSession对象执行对应的SQL语句,并返回结果。 4. 在执行SQL语句之前,MyBatis会进行参数解析和类型转换等操作。可以分析这部分代码,了解参数处理的过程。 5. SQL语句的执行过程中,还涉及到一些与数据库连接相关的操作,比如连接的获取和释放。可以查看这部分代码,了解连接管理的实现方式。 6. 最后,可以分析SQL语句的执行结果处理过程。MyBatis会根据XML映射文件中定义的结果映射规则,将查询结果转换成相应的Java对象。 需要注意的是,MyBatis码比较庞大复杂,以上只是对Mapper码分析的一般步骤。具体的分析过程可能会因版本和具体使用情况而有所不同。建议先阅读MyBatis的官方文档和相关资料,对其基本原理有所了解,再进行码分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠然予夏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值