查询数据库两列为Map(3种方式)

您所在的位置:网站首页 groovy拿shell返回数据 查询数据库两列为Map(3种方式)

查询数据库两列为Map(3种方式)

2023-09-14 04:39| 来源: 网络整理| 查看: 265

问题描述

SELECT两个字段,需要返回一个Map,其中第一个字段作为key,第二个字段作为value

解决方案

推荐第三种解决方案

1.封装结果集

编写ResultMap,映射字段值和key/value的关系

select "SCName" , "SCValue" from "SystemCongfigures" where "SCName" like #{SCName}

使用@MapKey指定需要作为key值的属性(实际上是拦截器) 详细拦截器方式可查看(https://www.cnblogs.com/waterystone/p/6214322.html.)

@MapKey("key") public Map selectBySCName(@Param("SCName") String SCName);

按照以上的方式,会把查询得到的每一行数据封装成一个Map(key=SCName,value=SCValue),然后把所有的Map又以SCName为key,都封装进一个Map中,没有达到我想要的效果,只能自己定义一个类,属性为查询出的两个字段,然后将步骤2中Map后面的Object相应替换掉,@MapKey("")指定哪个属性作为key值。

2.重新mybatis的handle方式(比较麻烦)

映射resultMap和第1种方式中的写法一样 key 对应一列,value对应一列。

import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import java.util.HashMap; import java.util.Map; // yanghaiyun 重写返回mybatis返回map public class SelectMapKeyAndValue implements ResultHandler { @SuppressWarnings("rawtypes") private final Map mappedResults = new HashMap(); @SuppressWarnings("unchecked") @Override public void handleResult(ResultContext context) { @SuppressWarnings("rawtypes") Map map = (Map) context.getResultObject(); mappedResults.put(map.get("key"), map.get("value")); // xml 配置里面的property的值,对应的列 } @SuppressWarnings("rawtypes") public Map getMappedResults() { return mappedResults; }

sqlSession.java

import com.at21.nsbd.inspection.common.utils.SelectMapKeyAndValue; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Map; @Service public class SessionMapper extends SqlSessionDaoSupport { @Resource public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } /** * @return */ @SuppressWarnings("unchecked") public Map selectWorkMap(String id){ SelectMapKeyAndValue handler = new SelectMapKeyAndValue(); //namespace : XxxMapper.xml 中配置的地址(XxxMapper.xml的qualified name) //.selectXxxxNum : XxxMapper.xml 中配置的方法名称 //this.getSqlSession().select(namespace+".selectXxxxNum", handler); String planScheduleId = id; this.getSqlSession().select(PlanWorkInfoDetailRepository.class.getName()+".selectPlanWorkInfoMap",planScheduleId, RowBounds.DEFAULT, handler); Map map = handler.getMappedResults(); return map; } 3.代码处理

selectAll()用的是tk mybatis 通用mapper

public Map selectUserNameMap() { List userInfoList = userInfoMapper.selectAll(); return userInfoList.stream() .filter(Objects::nonNull) .collect(Collectors.toMap(UserInfo::getUserName, UserInfo::getChineseName)); }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3