参考文章: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);
}