参考的这位大神的:https://blog.csdn.net/jlh912008548/article/details/62884627
自己记录一下,以备下次使用
在使用MyBatis查询数据库时,我们有时候需要查询两列数据,一列做map的key,一列作为map的value,然后将查询出的结果以map的形式返回。
比如我们的数据库表为test
create table test
(
name varchar(32),
age int,
...
)
现在我们需要将name作为key,age作为value返回map,首先在test对应的mapper.xml中配置resultMap和查询语句如下:
<resultMap id="mapNameAge" type="HashMap">
<result property="key" column="myname" javaType="java.lang.String"/>
<result property="value" column="myage" javaType="java.lang.String" />
</resultMap>
<select id="queryNameAge" resultMap="mapNameAge">
select name as myname, age as myage from test
</select>
然后,我们需要定义ResultHandler
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
public class MapResultHandler 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;
}
}
接着,写我们自己的session查询MapSessionMapper
@Repository
public class MapSessionMapper extends SqlSessionDaoSupport {
//namespace : XxxMapper.xml 中配置的地址(XxxMapper.xml的qualified name)
//.selectXxxxNum : XxxMapper.xml 中配置的方法名称
//this.getSqlSession().select(namespace+".selectXxxxNum", handler);
@Resource
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
@SuppressWarnings("unchecked")
public Map<String,String> queryNameAge() {
MapResultHandler handler = new MapResultHandler();
// this.getSqlSession().select(namespace+".methodName", handler);
// namespace: xxxdao.xml文件中mapper的namespace值
// methodName:xxxdao.xml文件中定义的方法名queryNameAge
this.getSqlSession().select(TblAgentDao.class.getName()+".queryNameAge", handler);
Map<String,String> map = handler.getMappedResults();
return map;
}
}
在service中调用:
@Autowired
MapSessionMapper mapSessionMapper;
public void test() {
Map<String, String> mapNameAge = mapSessionMapper.queryNameAge();
}