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

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

题目不让加<> 符号

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

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

Service

       public Map getDeviceCollectStateIdByBean(Map parameter) 

ServiceImpl

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

Dao 

    public Map getDeviceCollectStateIdByBean(Map parameter);

DaoImpl

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

Mapper

	

测试打印结果

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




你可能感兴趣的:(MyBatis)