zoukankan      html  css  js  c++  java
  • mybatis源码追踪2——将结果集映射为map

    org.apache.ibatis.binding.MapperMethod中execute方法

    ...
    } else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } else {
    ...
      private <K, V> Map<K, V> executeForMap(SqlSession sqlSession, Object[] args) {
        Map<K, V> result;
        Object param = method.convertArgsToSqlCommandParam(args);
        if (method.hasRowBounds()) {
          RowBounds rowBounds = method.extractRowBounds(args);
          result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey(), rowBounds);
        } else {
          result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey());
        }
        return result;
      }

    映射为map时有个可自定义的参数:mapkey

        private String getMapKey(Method method) {
          String mapKey = null;
          if (Map.class.isAssignableFrom(method.getReturnType())) {
            final MapKey mapKeyAnnotation = method.getAnnotation(MapKey.class);
            if (mapKeyAnnotation != null) {
              mapKey = mapKeyAnnotation.value();
            }
          }
          return mapKey;
        }

    通过org.apache.ibatis.annotations.MapKey可以配置该参数,该参数应与sql中select的字段一致且为大写。

    最终的resultHandler:

    public class DefaultMapResultHandler<K, V> implements ResultHandler {
    
      private final Map<K, V> mappedResults;
      private final String mapKey;
      private final ObjectFactory objectFactory;
      private final ObjectWrapperFactory objectWrapperFactory;
    
      @SuppressWarnings("unchecked")
      public DefaultMapResultHandler(String mapKey, ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory) {
        this.objectFactory = objectFactory;
        this.objectWrapperFactory = objectWrapperFactory;
        this.mappedResults = objectFactory.create(Map.class);
        this.mapKey = mapKey;
      }
    
      public void handleResult(ResultContext context) {
        // TODO is that assignment always true?
        final V value = (V) context.getResultObject();
        final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory);
        // TODO is that assignment always true?
        final K key = (K) mo.getValue(mapKey);
        mappedResults.put(key, value);
      }
    
      public Map<K, V> getMappedResults() {
        return mappedResults;
      }
    }
  • 相关阅读:
    通过python来获取网页状态
    php多域名跳转nginx
    mybatis-plus主键策略
    mybatis-plus ActiveRecord模式
    mybatis-plus-Cud操作
    mybatis-plus高级操作
    mybatis-plus入门
    ☕【Java技术指南】「序列化系列」深入挖掘FST快速序列化压缩内存的利器的特性和原理
    虚拟机研究系列-「GC本质底层机制」SafePoint的深入分析和底层原理探究指南
    👊 Spring技术原理系列(7)带你看看那些可能你还不知道的Spring特性技巧哦!
  • 原文地址:https://www.cnblogs.com/chanedi/p/4054219.html
Copyright © 2011-2022 走看看