1、自定义实现该类
package com.linmain.dict.handle;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("all")
public class MapResultHandle<K, V> implements ResultHandler<Map<K, V>> {
private final Map<K,V> mappedResults = new HashMap<>();
@Override
public void handleResult(ResultContext<? extends Map<K, V>> resultContext) {
Map map = (Map) resultContext.getResultObject();
mappedResults.put((K)map.get("key"), (V)map.get("value"));
}
public Map<K, V> getMappedResults() {
return mappedResults;
}
}
2、在抽象dao层书写返回map集合类型的方法
Map<String,String> pageByTypeId(Serializable typeId);
3、在XXXDao.xml文件中书写sql语句和resultMap类型
<resultMap id="mapResult" type="java.util.HashMap">
<result property="key" column="data_value"/>
<result property="value" column="data_name"/>
</resultMap>
<select id="pageByTypeId" resultMap="mapResult">
select data_name, data_value
from dict_data
where dict_id = #{typeId}
and is_delete = '0';
</select>
4、如何使用
@Override
public Map<String,String> getAllByTypeId(Serializable typeId) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
MapResultHandle<String, String> mapResultHandle = new MapResultHandle<>();
sqlSession.select("com.linmain.dict.dao.DictDataDao.pageByTypeId", typeId, mapResultHandle);
Map<String, String> mappedResults = mapResultHandle.getMappedResults();
return mappedResults;
}