Mybatis查询结果为两列时, 结果保存为key-value的map

mybatis查询结果为map时,出来的结果默认是下面这样的

[{
   key: 1,
   value: 'xx'     
},
{
   key: 2,
   value: 'xxx'
}]

我们想要的是这样的:

{
    1 : 'xx',
    2 : 'xxx'
}

如果自己转换的话非常麻烦。经过一番查找,发现mybatis可以在查询出来的时候通过修改handler自动转换

先写一个Handler继承ResultHandler

package;

import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

import java.util.HashMap;
import java.util.Map;

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

    @SuppressWarnings("unchecked")
    @Override
    public void handleResult(ResultContext context) {
        @SuppressWarnings("rawtypes") Map map = (Map) context.getResultObject();
        // xml配置中通过resultMap配置的property
        mappedResults.put(map.get("key"), map.get("value"));
    }

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

 

Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.coreDB.NationnalityCodeMapper">
  <resultMap id="BaseResultMap" type="com.coreDB.NationnalityCodePO">
    <id column="NATIONALITY_CODE" jdbcType="VARCHAR" property="nationalityCode" />
    <result column="NATIONALITY_DESC" jdbcType="VARCHAR" property="nationalityDesc" />
  </resultMap>

  <resultMap id="mapResult" type="HashMap">
  <!-- 这里的property需要与handler中map.get的名称对应 -->
<result property="key" column="NATIONALITY_CODE" javaType="java.lang.String"/> <result property="value" column="NATIONALITY_DESC" javaType="java.lang.String" /> </resultMap>

<select id="selectAllMap" resultMap="mapResult"> select NATIONALITY_CODE, NATIONALITY_DESC from T_NATIONALITY_CODE </select> </mapper>

 

需要查询时,不使用原来的mapper接口,新建一个查询类,使用@Repository注入并且继承SqlSessionDaoSupport,从而可以获取SqlSession对象

import MapResultHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Map;

@Repository
public class MapSessionMapper extends SqlSessionDaoSupport {
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

   
    public Map<String, String> selectCountryMap() {
        MapResultHandler handler = new MapResultHandler();
        this.getSqlSession().select(NationnalityCodeMapper.class.getName() + ".selectAllMap", handler);
        Map<String, String> map = handler.getMappedResults();
        return map;
    }
}

NationnalityCodeMapper

@Mapper
public interface NationnalityCodeMapper {
   //这里不需要写接口,因为改造后的方法是通过MapSessionMapper来调用的
}

 

调用方式如上,通过获取SqlSession来调用sql并使用我们自己定义的handler解析结果,selectAllMap是我这里的业务方法名称,sql实现依旧在XML中编写

 

posted @ 2020-02-26 11:21  一秋复一秋  阅读(3543)  评论(0编辑  收藏  举报