实现MyBatis查询返回值Map(String,Object)
程序员文章站
2022-03-04 22:20:52
...
今天有一个需求需要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);
上一篇: GBase 8c 全文检索-表检索
推荐阅读
-
mybatis:查询参数为map,返回值为list
-
转:代码实现:MyBatis查询,返回值Map或List
-
MyBatis查询,返回值Map或List
-
MyBatis查询,返回值Map或List
-
jdbc查询返回来的List
-
Mybatis传入 List<Map<String,Object>>的入参
-
mybatis 插入List<Map<String, Object>> 出现__frch_list_0异常
-
mybatis_批量插入参数List_Map_String,Object
-
使用 Mybatis 实现数据库的增删改查、Map和模糊查询
-
使用 Mybatis 实现数据库的增删改查、Map和模糊查询