1. Requirements: When the Mybatis query result set is a Map, the key in the Map is the column name, and the value corresponding to the key is the column value corresponding to the column. The requirements in the project are that the value corresponding to field A is used as the key of the Map, and the value corresponding to field B is used as the value corresponding to the key.
2. Implementation idea: rewrite the ResultHandler interface, and then use the select method of SqlSession to configure the return value of the mapping file in the xml as a HashMap.
3. Code implementation:
(1) xml placement:
<resultMap id="ipNumResult" type="java.util.HashMap">
<result property="key" column="requestUrl"/>
<result property="value" column="num"/>
</resultMap>
<select id="getAccessUrlNum" resultMap="ipNumResult">
select a.request_url requestUrl, count(1) num from access_statistics a GROUP BY a.request_url;
</select>
(2) Implement the interface
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;
}
}
(3) calling class
public <K,V> Map<K,V> queryForMap(String statement, Object params) {
MapResultHandler handler = new MapResultHandler();
sqlSession.select(statement, params, handler);
return handler.getMappedResults();
}
Related links for reference materials: http://www.cnblogs.com/GoQC/p/6216967.ht