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(); //key和value是xml中映射的 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对象,true:自动提交 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; }
来源地址:https://blog.csdn.net/u011746120/article/details/129441077