一、自定义返回拦截器
package com.yaoex.crm.service.util;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @Title: MapResultHandler
* @Package: com.yaoex.crm.service.util
* @description:
**/
@Component
public class MapResultHandler implements ResultHandler {
private static final Logger log = LoggerFactory.getLogger(MapResultHandler.class);
private static SqlSessionTemplate sqlSessionTemplate;
@Autowired
public void setSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
MapResultHandler.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
}
@SuppressWarnings("rawtypes")
private final Map mappedResults = new HashMap();
@SuppressWarnings("unchecked")
@Override
public void handleResult(ResultContext context) {
@SuppressWarnings("rawtypes")
Map map = (Map) context.getResultObject();
if(map.get("key") != null && map.get("value") != null ){
// xml配置里面的property的值,对应的列
mappedResults.put(map.get("key"), map.get("value"));
}
}
@SuppressWarnings("rawtypes")
public Map getMappedResults() {
return mappedResults;
}
public static Map getMapResults(String statementId,Map<String,Object> param){
MapResultHandler handler = new MapResultHandler();
sqlSessionTemplate.select(statementId,param,handler);
return handler.getMappedResults();
}
}
二、mybatis配置
<resultMap id="levelCountMap" type="java.util.Map" >
<result column="cust_level" property="key" jdbcType="INTEGER" />
<result column="count" property="value" jdbcType="INTEGER" />
</resultMap>
<select id="selectCountByLevel" resultMap="levelCountMap">
SELECT l.cust_level,COUNT(l.cust_level) as count from t_crm_customer_level l
GROUP BY l.cust_level
</select>
三、调用方式
Map<Integer,Long> results = MapResultHandler.getMapResults("com.yaoex.crm.dao.customerdata.CrmCustomerLevelDao.selectCountByLevel", null);