mybatis查询多个结果返回map--@MapKey使用方法

       

目录

       

介绍

 源码分析:


介绍

在使用mybatis的时候遇到一种情况,查询结果集返回多个,想用map接收,以前是用List<对象>接收,然后java代码中转换成map。其实mybatis是支持返回map的。下面就介绍使用方法。

测试代码:

@GetMapping(value = "dd")
    public String test4(String params){

        log.info("dsds" + params);

        Map map = businessPriceMapper.getmaphh();
        log.info("dsva ",map);
        // 保存数据
        return "1122";
    }

下面@MapKey中的id是BusinessPricePO中的一个属性id,否则会报错:There is no getter for property named 'id' in 'class java.lang.Class' 

public interface BusinessPriceMapper extends BaseMapper {

    @MapKey("id")
    Map getmaphh();
}

查询结果:

mybatis查询多个结果返回map--@MapKey使用方法_第1张图片

 源码分析:

在spring-boot继承mybatis,执行的时候会进入com.baomidou.mybatisplus.core.override.MybatisMapperMethod#execute

这个类,不同继承方式不同,这个自己打断点进入,查看

mybatis查询多个结果返回map--@MapKey使用方法_第2张图片

执行进入:com.baomidou.mybatisplus.core.override.MybatisMapperMethod#executeForMap 

private  Map executeForMap(SqlSession sqlSession, Object[] args) {
        Map result;
        Object param = method.convertArgsToSqlCommandParam(args);
        if (method.hasRowBounds()) {
            RowBounds rowBounds = method.extractRowBounds(args);
            result = sqlSession.selectMap(command.getName(), param, method.getMapKey(), rowBounds);
        } else {
// 执行这里的查询map方法
            result = sqlSession.selectMap(command.getName(), param, method.getMapKey());
        }
        return result;
    }

 再执行:org.apache.ibatis.session.defaults.DefaultSqlSession#selectMap(java.lang.String, java.lang.Object, java.lang.String, org.apache.ibatis.session.RowBounds)

mybatis查询多个结果返回map--@MapKey使用方法_第3张图片

public  Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
    final List list = selectList(statement, parameter, rowBounds);
    final DefaultMapResultHandler mapResultHandler = new DefaultMapResultHandler<>(mapKey,
            configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory());
    final DefaultResultContext context = new DefaultResultContext<>();
    for (V o : list) {
// 将返回结果,循环处理放入context中
      context.nextResultObject(o);
// 这里再进行转换
      mapResultHandler.handleResult(context);
    }
// 处理完,再拿出转换后的结果,返回
    return mapResultHandler.getMappedResults();
  }

 处理返回Map的handler

org.apache.ibatis.executor.result.DefaultMapResultHandler#handleResult

public void handleResult(ResultContext context) {
    final V value = context.getResultObject();
    final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory, reflectorFactory);
    // TODO is that assignment always true?
// 通过反射,找到key的get方法,再获取值
    final K key = (K) mo.getValue(mapKey);
// 将对象转换为map
    mappedResults.put(key, value);
  }

最终返回。

你可能感兴趣的:(mybatis-plus学习,mybatis,java,mysql)