目录
介绍
在使用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);
}
最终返回。
这篇博客介绍了如何在 MyBatis 中使用 Map 来接收查询结果。通过在 Mapper 方法上添加 @MapKey 注解,可以指定映射的键,从而将查询结果自动转换为 Map。示例代码展示了在 Spring Boot 环境下,从 BusinessPricePO 对象集合转换为 Long 到 BusinessPricePO 的 Map,并解析了 MyBatis 执行查询时的源码流程。
1424

被折叠的 条评论
为什么被折叠?



