Mybatis select返回值為map時,選取表字段的兩列作為key,value


項目需要從ibatis升級到MyBatis,dao中有一個方法返回Map類型,具體是查詢語句查詢兩個字段,將結果列表字段A的值作為key字段B的值作為value存入Map中作為結果返回;

ibatis中Dao繼承SqlMapClientDaoSupport類的queryForMap(String statement, Object param, String key, String value)方法可直接實現;

MyBatis的SqlSession中只有selectMap(String statement, Object parameter, String mapKey),此方法將結果集中指定字段作為key,value則是結果集列表的元素對象們;源碼如下:

/**
   * The selectMap is a special case in that it is designed to convert a list
   * of results into a Map based on one of the properties in the resulting
   * objects.
   * @param <K> the returned Map keys type
   * @param <V> the returned Map values type
   * @param statement Unique identifier matching the statement to use.
   * @param parameter A parameter object to pass to the statement.
   * @param mapKey The property to use as key for each value in the list.
   * @return Map containing key pair data.
   */
  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);

上網查了一些博文,最終參考:http://blog.csdn.net/sou_liu/article/details/47755635,整理如下:

主要思想是:重寫ResultHandler接口,,然后用SqlSession 的select方法,將xml里面的映射文件的返回值配置成 HashMap 就可以了。

xml配置:

<resultMap id="ipDeptResult" type="java.util.HashMap">
    <result property="key" column="ip"/>
    <result property="value" column="dept"/>
</resultMap>

sql查詢語句select出兩個字段ip和dept,resultMap配置成上面定義的那個ipDeptResult。

看看Handler的實現就知道為什么resultMap里面的property寫成key和value了,其實完全是自定義的。Handler對結果集的每一條記錄調用handleResult方法我們重寫它進行格式轉換。

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的值,對應的列
    }
    public Map getMappedResults() {
        return mappedResults;
    }
}

調用類:

@Override
public <K,V> Map<K,V> queryForMap(String statement, Object params) {
    MapResultHandler handler = new MapResultHandler();
    sqlSession.select(statement, params, handler);
    return handler.getMappedResults();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM