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

       

目录

       

介绍

 源码分析:


介绍

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

测试代码:

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

        log.info("dsds" + params);

        Map<Long, BusinessPricePO> 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<BusinessPricePO> {

    @MapKey("id")
    Map<Long, BusinessPricePO> getmaphh();
}
<select id="getmaphh" resultType="com.ccreate.cnpc.apply.entity.BusinessPricePO">
        SELECT id,apply_id FROM business_price LIMIT 10
    </select>

查询结果:

 源码分析:

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

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

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

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.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)

public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
    final List<? extends V> list = selectList(statement, parameter, rowBounds);
    final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<>(mapKey,
            configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory());
    final DefaultResultContext<V> 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<? extends V> 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);
  }

最终返回。

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis 中的 @MapKey 注解和 resultMap 中的 <map> 标签都用于将查询结果转换为 Map 类型,但它们的使用方式略有不同。 @MapKey 注解用于将查询结果集中的某一列作为 Map 的键,将整个结果集放入 Map返回。它通常与 selectMap() 方法一起使用,示例如下: ```java @MapKey("id") Map<Integer, User> selectUserMap(); ``` 上述代码中,@MapKey("id") 注解指定将查询结果集中的 id 列作为 Map 的键,将整个结果集转换为 Map<Integer, User> 类型返回。 而 <map> 标签则用于将查询结果集中的多列转换为一个 Map 类型的属性,通常用于一对多关系的映射。示例如下: ```xml <resultMap id="orderMap" type="Order"> <id property="id" column="id"/> <result property="orderNo" column="order_no"/> <result property="createTime" column="create_time"/> <collection property="orderItems" ofType="OrderItem"> <id property="id" column="item_id"/> <result property="name" column="item_name"/> <result property="quantity" column="item_quantity"/> </collection> <map property="extra" columnPrefix="extra_"> <key column="name"/> <value column="value"/> </map> </resultMap> ``` 上述代码中,<map> 标签用于将查询结果集中以 extra_ 前缀开头的多列转换为一个 Map<String, Object> 类型的属性,其中 name 列作为 Map 的键,value 列作为 Map 的值。 需要注意的是,@MapKey 注解和 <map> 标签都需要指定一个属性作为 Map 的键,如果没有指定,则默认将整个查询结果集转换为 Map 类型返回
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值