mybatis返回兩個字段分別作爲map的key和value

參考文章:https://blog.csdn.net/llmys/article/details/80362280

                 https://blog.csdn.net/jlh912008548/article/details/62884627

基本分爲三步:

第一步:在mapper.xml裏寫好你要查詢的sql,resultMap要自定義,配置key和value

<resultMap id="TargetMapResult" type="HashMap">
    <result peoperty="key" column="mon" jdbcType="TINYINT" javaType="INTERGER"/>
    <result peoperty="value" column="amo" jdbcType="TINYINT" javaType="INTERGER"/>
</resultMap>
<select id="getMonAndAmo" parameterType="java.lang.Integer" resultMap="TargetMapResult">
select mon,amo from biao where type=#{type}
<select>

第二步:寫ResultHandler,實現ibatis.session包下的ResultHandler,對返回數據進行轉map處理

import org.apache.ibatis.session.ResultMap;
import java.util.HashMap;
import java.util.Map;

public class ResultHandler implements org.apache.session.ResultHandler{
    private final Map mappedResult=new HashMap();

    @Override
    public void handleResult(ResultContext resultContext){
        Map resultMap = (Map)resultContext.getResultObject();
        mappedResults.put(resultMap.get("key"),resultMap.get("value"));
    }

    public Map getMappedResults(){
        return mappedResults;
    }
}

 

第三步:自定義mapper,注入sqlSession,在sqlSession裏使用我們定義好的handler

@Repository
public class MapSessionMapper extends SqlSessionDaoSupport{
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
        super.setSqlSessionFactory(sqlSessionFactory);
    }
    
    public Map<Integer,Integer> getMonAndAmoMap(){
        ResultHandler hanlder =new ResultHandler();

//第一個參數,是mapper.xml的namespace的類,
//第二個參數,是我們mapper.xml裏的參數
//第三個參數,我們自定義的handler   
     
 this.getSqlSession().select(XXXxMapper.class.getName()+".getMonAndAmoMap",1,handler);
    Map mappedResults = handler.getMappedResults();
    return mappedResults;
    }
}

寫測試類

//在你的測試類裏面,注入你剛寫的MapSessionMapper
@Autowired
private MapSessionMapper mapSessionMapper;

@Test
public void testMapSessionMapper(){
    Map<Integer,Integer> map =mapSessionMapper.getMonAndAmoMap();
    System.out.println(map);
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章