sql查询返回值使用map封装多个key和value

2022-06-29 12:37:32

sql查询返回值使用map封装多个key和value

直接上代码,代码是测试过的

1.重写ResultHandler

publicclassMapResultHandlerimplementsResultHandler{privatefinal Map mappedResults=newHashMap();@OverridepublicvoidhandleResult(ResultContext context){@SuppressWarnings("rawtypes")
        Map map=(Map) context.getResultObject();
        mappedResults.put(map.get("key"), map.get("value"));}public MapgetMappedResults(){return mappedResults;}}

2.在mapper封装

<resultMap id="retMap"type="java.util.HashMap"><resultcolumn="keyName" property="key" javaType="java.lang.String"/><resultcolumn="val" property="value" javaType="java.math.BigDecimal"/></resultMap> 
    例子:SELECT F_NAME keyName,nvl(sum(F_METADATA_VALUE),0) valfrom 表名GROUPBY F_CODE, F_NAME

3.service实现

@Autowiredprivate SqlSessionFactory sqlSessionFactory;privatestaticfinal String mapperPath="mapper的路径.";      

  Map<String, Object> parameter=newHashMap<>();//设置参数
        parameter.put("query", query);//mapper的方法名
        String methodName="selectMedicineSurvey";//查询数据使用Map封装
        Map<String, BigDecimal> medicineSurveyMap=getStringBigDecimalMap(mapperPath, parameter, methodName);//查询数据使用Map封装private Map<String, BigDecimal>getStringBigDecimalMap(String mapperPath, Map<String, Object> parameter, String methodName){
        SqlSession sqlSession= sqlSessionFactory.openSession(true);
        MapResultHandler handler=newMapResultHandler();
        sqlSession.select(mapperPath+ methodName, parameter, handler);//关流
        sqlSession.close();//获取结果return(Map<String, BigDecimal>) handler.getMappedResults();}

sqlSession.close();
一定要记得数据库关流,不然连接数就会把数据库给卡死

  • 作者:几痴~
  • 原文链接:https://blog.csdn.net/weixin_45245297/article/details/106604533
    更新时间:2022-06-29 12:37:32