Mybatis 返回map返回两列值 分别为key value

Mybatis 返回map返回两列值 分别为key value

一 先在Mapper.xml 添加key 和 value 的对应值

<resultMap id="mapResultMap" type="HashMap">
    <result property="key" column="deviceCode"  javaType="java.lang.String" />
    <result property="value" column="value" javaType="java.lang.String" jdbcType="VARCHAR" />
  </resultMap>

<select id="selectDeviceHost" resultMap="mapResultMap" parameterType="Map">
    SELECT CONCAT(recordTime,',',device_code)as deviceCode,value from (
    SELECT
    energy_item_his_id,device_code,param_type_code,value,unit,
 </select>

注:CONCAT(recordTime,’,’,device_code) mysql 字段拼接

二,实现ResultHandler的实现类(将map结果进行对应的封装)

public class MyResultHandler implements ResultHandler {
    @SuppressWarnings("rawtypes")
    private final HashMap mappedResults = new HashMap();

    @SuppressWarnings("unchecked")
    @Override
    public void handleResult(ResultContext context) {
        @SuppressWarnings("rawtypes")
        Map map = (Map) context.getResultObject();
        mappedResults.put(map.get("key"), map.get("value")); // xml配置里面的property的值,对应的列
    }

    @SuppressWarnings("rawtypes")
    public HashMap getMappedResults() {
        return mappedResults;
    }
}

三,一个实现SqlSessionDaoSupport 接口的实现类 (在其中调用重写了ResultHandler的实现类的方法)

@Repository
public class SessionMapper extends SqlSessionDaoSupport {

    @Override
    @Resource
    @Autowired
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    /**
     * @return
     */
    @SuppressWarnings("unchecked")
    public HashMap<String,String> selectDeviceHost(Map paramMap){
        MyResultHandler handler = new MyResultHandler();
        SessionMapper sessionMapper=new SessionMapper();
        //namespace : XxxMapper.xml 中配置的地址(XxxMapper.xml的qualified name)
        //.selectXxxxNum : XxxMapper.xml 中配置的方法名称
        //this.getSqlSession().select(namespace+".selectXxxxNum", handler);
        this.getSqlSession().select(DataDeviceEnergyHistoryMapper.class.getName()+".selectDeviceHost",paramMap, handler);
        HashMap<String, String> map = handler.getMappedResults();
        return map;
    }
}

四,相应的service 层进行调用 OK

     Map   mapEnd=sessionMapper.selectDeviceHost(maParam);

注·:其实就是重写了mybatis的一套调用流程 使用我们自己重写后的方法实现查询结果的封装.

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值