import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import java.util.HashMap;
import java.util.Map;
/**
* @Desc
* @Creator Hardy
* @Create_Date 2022/3/4 9:40
* @Updater
* @Update_Date
**/
public class MapResultHandler implements ResultHandler<Map> {
private final Map<String, String> mappedResults = new HashMap();
@Override
public void handleResult(ResultContext resultContext) {
Map<String, String> m = (Map) resultContext.getResultObject();
mappedResults.put(m.get("key"), m.get("value"));
}
public Map getMappedResults() {
return mappedResults;
}
}
dao层
void getMixingPlantProductionSummary() String devSNs, MapResultHandler mapResultHandler);
引用
MapResultHandler handler = new MapResultHandler();
xxxDao.getMixingPlantProductionSummary(orgId, devSNs, handler);
Map resultMap = handler.getMappedResults();
mapper.xml
<resultMap id="mapResult" type="java.util.HashMap">
<result property="key" column="name"/>
<result property="value" column="count"/>
</resultMap>
<select id="getMixingPlantProductionSummary" resultMap="mapResult">
SELECT
gsom.intensity_level AS name,
SUM(gsom.quantity) AS count
FROM
gt_szls_out_master gsom
<where>
<if test="orgId != null">
and gsom.org_id = #{orgId}
</if>
<if test="devSNs != null">
and gsom.dev_sn in (#{devSNs})
</if>
</where>
GROUP BY gsom.intensity_level
</select>
注意:
1、xxxDao.java中定义的接口返回值类型必须是void,如上面void getMixingPlantProductionSummary()
2、MyBatis.xml中定义的resultMap返回值类型是HashMap,其里面定义的两个result中的key要与MapResultHandler.java中代码mappedResults.put(m.get("key"), m.get("value"))保持一致;其value属性必须和Mybatis.xml中sql的返回值名称一致
3、Map resultMap = handler.getMappedResults();中的resultMap就是我们一开始讲到的前端需要的数据类型