zoukankan      html  css  js  c++  java
  • Mybatis select返回值为map时,选取表字段的两列作为key,value

    转自:http://blog.csdn.net/sou_liu/article/details/47755635

    最近需要用到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;
    

      

  • 相关阅读:
    Collection(集合)知识点总结
    【Mysql 学习】mysql 的使用复习
    解决Address localhost:1099 is already in use
    mysql8.0中dcl语句修改密码的语法
    mysql+sqlyog 多表查询练习
    MySQL 8.0 Public Key Retrieval is not allowed 错误的解决方法
    JDBC连接Mysql 8.0.12版本的几个注意事项
    JSTL学习
    64-多个参数个数
    63-参数的使用
  • 原文地址:https://www.cnblogs.com/sunada2005/p/5716516.html
Copyright © 2011-2022 走看看