最近需要用到Mybatis中查询结果集为Map的功能,查了好多资料,最终搞定。其实只需要重写ResultHandler接口,,然后用SqlSession 的select方法,将xml里面的映射文件的返回值配置成 HashMap 就可以了。具体过程如下
1、先看看xml文件怎么配置
<resultMap id="getAllSetDaysResult" type="HashMap"> <result property="key" column="SP_FPARAMEKEY" /> <result property="value" column="SP_FPARAMEVALUE" /> </resultMap>
2、sql
<select id="getAllSetDays" resultMap="getAllSetDaysResult"> SELECT SP.FPARAMEKEY SP_FPARAMEKEY, SP.FPARAMEVALUE SP_FPARAMEVALUE FROM T_SERVER_PARAMETER SP WHERE SP.FPARAMEKEY IN ('XXX') </select>
3、重写org.apache.ibatis.session 中ResultHandler接口:
public class FblMapResultHandler 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的值,对应的列 } public Map getMappedResults() { return mappedResults; } }
4、调用select方法:
FblMapResultHandler fbl = new FblMapResultHandler(); getSqlSession().select(NAMESPACE +"getAllSetDays",fbl); @SuppressWarnings("rawtypes") Map map =fbl.getMappedResults(); return map;