MyBatis3源码解析(7)TypeHandler注册与获取

简介

在上篇文章中,我们介绍了TypeHandler的简单使用和解析了TypeHandler的处理核心,这篇文章中我们接着看到TypeHandler是如注册和获取使用的

源码解析

TypeHandler注册

typeHandler注册的函数代码如下:

  • 根据JavaType放入第一层Map
  • 根据jdbcType放入第二层Map
  configuration.getTypeHandlerRegistry().register(String[].class, JdbcType.VARCHAR, StringArrayTypeHandler.class);

  private void register(Type javaType, JdbcType jdbcType, TypeHandler<?> handler) {
   
    if (javaType != null) {
   
      Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.get(javaType);
      if (map == null || map == NULL_TYPE_HANDLER_MAP) {
   
        map = new HashMap<>();
      }
      map.put(jdbcType, handler);
      typeHandlerMap.put(javaType, map);
    }
    allTypeHandlersMap.put(handler.getClass(), handler);
  }

TypeHandler获取

在探索中,我们发现是在Mapper初始化的过程就会去获取TypeHandler了,在示例代码中我们调用了函数:addMapper

在该函数中,我们看到了我们熟悉的(前面文章分析过,Sql执行其实就是从Mapper代理类开始的)MapperProxy相关的东西

  public <T> void addMapper(Class<T> type) {
   
    if (type.isInterface()) {
   
      if (hasMapper(type)) {
   
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
   
	      // 生成我们熟悉的Mapper代理类
        knownMappers.put(type, new MapperProxyFactory<>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
	// 进行解析
        parser.parse();
        loadCompleted = true;
      } finally {
   
        if (!loadCompleted) {
   
          knownMappers.remove(type);
        }
      }
    }
  }

跟踪下面,我们看到SQLSource生成的相关代码,ParameterMapper就是从SQLSource带下去的

  void parseStatement(Method method) {
   
    ......
    getAnnotationWrapper(method, true, statementAnnotationTypes).ifPresent(statementAnnotation -> {
   
      final SqlSource sqlSource = buildSqlSource(statementAnnotation.getAnnotation(), parameterTypeClass, languageDriver, method);
      ......
    });
  }

  public SqlSource createSqlSource(Configuration configuration, String script, Class
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值