Mapper 接口方法如何与注解里的 SQL 进行绑定的?

    科技2026-06-05  9

    根据 Mapper 接口、其方法、方法上的注解,生成 mappedStatementId 与 MapperStatement,注册到 configuration 对象中

    根据 Mapper 接口方法查到并调用对应的 MappedStatement,执行 SQL

    流程与 Mapper 接口与 xml 绑定类似。

     

    分析

    解析生成注册 MapperStatement 的代码入口在 MapperRegistry addMapper 方法

    //使用 MapperProxyFactory 包装 Mapper 接口 Class 对象 knownMappers.put(type, new MapperProxyFactory<>(type)); //解析 Mapper 接口方法上的注解,生成对应的 MapperStatement MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); parser.parse();

     

    获取 Mapper 接口的动态代理对象的代码入口在 MapperRegistry getMapper 方法

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {     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);     } }

     

     


    【Java面试题与答案】整理推荐

    基础与语法集合网络编程并发编程Web安全设计模式框架算法与数据结构异常文件解析与生成LinuxMySQLOracleRedisDubbo

     

    Processed: 0.014, SQL: 9