Mybatis返回Map,List<Map>

            上次写[简单]Spring_Mybatis_CRUD简单示例(带数据库)遇到一个问题,在返回Map类型时候没有解析正确,不得不返回一个JavaBean,趁着有空,重新看了下,现在可以用Mybatis返回Map,List<Map>了

            返回Map,Mybatis配置如下

           

<select id="getCountyHashMap" resultType="java.util.HashMap">
		select name,id from
		tsql_test_region where
		id=#{id}
	</select>

    ServiceImpl如下

  

public Map<String, Long> getCountyHashMap(long id) {
		Map<String, Object> regionMap = regionInfoMapper.getCountyHashMap(id);
		Map<String, Long> resultMap = new HashMap<String, Long>();
		String region = null;
		Long vid = null;
		for (Map.Entry<String, Object> entry : regionMap.entrySet()) {
			if ("NAME".equals(entry.getKey())) {
				region = (String) entry.getValue();
			} else if ("ID".equals(entry.getKey())) {
				vid = ((java.math.BigDecimal) entry.getValue()).longValue();
			}
		}
		resultMap.put(region, vid);
		return resultMap;
	}

    Controller如下:

  

@RequestMapping(value = "/region3", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Long> getCountyMap(@RequestParam(required = true) int regionId) {
		return regionInfoService.getCountyHashMap(regionId);
	}

    结果为

 

   

     返回List<Map>类似:

     Mybatis配置:

  

<select id="getRegionHashMap" resultType="java.util.HashMap">
		select name,id from
		tsql_test_region order by id
	</select>

   ServiceImpl如下:

  

public Map<String, Long> getRegionHashMap() {
		List<Map<String, Object>> regionMap = regionInfoMapper
				.getRegionHashMap();
		Map<String, Long> resultMap = new HashMap<String, Long>();
		for (Map<String, Object> map : regionMap) {
			String region = null;
			Long id = null;
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if ("NAME".equals(entry.getKey())) {
					region = (String) entry.getValue();
				} else if ("ID".equals(entry.getKey())) {
					id = ((java.math.BigDecimal) entry.getValue()).longValue();
				}
			}
			resultMap.put(region, id);
		}
		return resultMap;
	}

   Controller如下:

  

@RequestMapping(value = "/region2", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Long> getRegionMap() {
		return regionInfoService.getRegionHashMap();
	}

    结果为

 

   

      本文系原创,转载请注明出处,谢谢

      全文完。

   

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值