1、自定義實(shí)現(xiàn)該類
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;
/**
* @Author linzhuoqi
* @Date 2023/3/9
* @Eamil 1580752420@qq.com
* @Version
* @Description 新建一個(gè)mappedResults,每次感應(yīng)到數(shù)據(jù)進(jìn)來,處理下然后塞進(jìn)去。
*/
@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類型
<!-- result類型 -->
<resultMap id="mapResult" type="java.util.HashMap">
<result property="key" column="data_value"/>
<result property="value" column="data_name"/>
</resultMap>
<!-- 上述方法的sql語句 -->
<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) {
//獲取一個(gè)sqlsession對(duì)象,true:自動(dòng)提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//創(chuàng)建一個(gè)結(jié)果處理器
MapResultHandle<String, String> mapResultHandle = new MapResultHandle<>();
//進(jìn)行數(shù)據(jù)查詢和結(jié)果封裝
sqlSession.select("com.linmain.dict.dao.DictDataDao.pageByTypeId", typeId, mapResultHandle);
Map<String, String> mappedResults = mapResultHandle.getMappedResults();
return mappedResults;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-548501.html
文章來源:http://www.zghlxwxcb.cn/news/detail-548501.html
到了這里,關(guān)于mybatisPlus返回Map類型的集合(兩列字段,一列為key,一列為value)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!