实现MyBatis查询返回值Map(String,Object)

今天有一个需求需要MyBatis返回值格式为Map<String,bean>,找了一些帖子和资料,自己研究半天终于解决。

题目不让加<> 符号

重写org.apache.ibatis.session 中ResultHandler接口

    public class FblMapResultHandler implements ResultHandler {  
	@SuppressWarnings("rawtypes") 
    private final  Map<String, DeviceBean> mappedResults = new HashMap<String, DeviceBean>() ;
	@SuppressWarnings("unchecked")
    @Override  
    public void handleResult(ResultContext context) {  
        @SuppressWarnings("rawtypes")  
        Map<String,Object> paramap=new HashMap<String,Object>();
        DeviceBean deviceBean =  (DeviceBean) context.getResultObject();
        String code = deviceBean.getCode();
        mappedResults.put(code, deviceBean);       
    }  
    public  Map<String, DeviceBean> getMappedResults() {    
        return mappedResults;    
    }    
}  

Service

       public Map<String, DeviceBean> getDeviceCollectStateIdByBean(Map<String, Object> parameter) 

ServiceImpl

    @Override
    public Map<String, DeviceBean> getDeviceCollectStateIdByBean(Map<String, Object> parameter) {
    logger.info("DeviceServiceImpl{}==>getDeviceCollectStateIdByBean()");
    return deviceDao.getDeviceCollectStateIdByBean(parameter);
    }

Dao 

    public Map<String, DeviceBean> getDeviceCollectStateIdByBean(Map<String, Object> parameter);

DaoImpl

	private final String namespace = "com..................Mapper.";
	public String sqlId(String method) {
		return namespace + method;
	}
	@Override	
	public Map<String, DeviceBean> getDeviceCollectStateIdByBean(Map<String, Object> parameter) {
		logger.info("DeviceDaoImpl{}==>getDeviceCollectStateIdByBean()");	
	      FblMapResultHandler fbl = new FblMapResultHandler();  
	       getWriteSession().select(sqlId("getDeviceCollectStateIdByBean"),parameter,fbl);  
	       @SuppressWarnings("rawtypes")  
	       Map<String, DeviceBean> map =fbl.getMappedResults();  
	       return map;  	       
	}

Mapper

	<select id="getDeviceCollectStateIdByBean" resultType="com.....DeviceBean" parameterType="map" >
	    select 
	    d.id as id, d.group_id as groupId,d.farm_id as farmId, d.house_id as houseId, d.code
	    from t_device d
	    WHERE  d.del_flag = '0' and d.code in 
	        <foreach item="item" index="index" collection="codelist" open="(" separator="," close=")">  
		  #{item}  
		</foreach>
	</select>

测试打印结果

	List<String>  codeList =new ArrayList<String>(); 
        codeList.add("b827ebee9322");
        codeList.add("111");
        codeList.add("1111");
        Map<String,Object> paramap=new HashMap<String,Object>();
        paramap.put("codelist", codeList); 
	Map<String, DeviceBean> res = deviceService.getDeviceCollectStateIdByBean(paramap);
	System.out.println(res);
	String test = res.get("111").getFarmName();
	System.out.println(test);




猜你喜欢

转载自blog.csdn.net/qq_36014509/article/details/80986373
今日推荐