mybatis返回多个map结果
如果返回一条结果,xml直接这样写:
dao中:
MapsearchncomedateByInvestID(investId);
如果返回多条结果,xml这样写:
dao中:
List
mybatis返回map类型的注意事项及小技巧
项目中为了避免定义java实体Bean,Mapper中往往会返回map类型。而返回map类型有几种定义方式:
1.resultType="java.util.Map"
接口中返回类型为Map
例如:
MapgetRoleInfo(@Param("userId")Integer id);
这种情况Map中的value返回值类型是由mysql数据库字段类型 jdbcType与javaType的对应关系决定具体是什么类型,其中role_level 数据库为int,对应的javaType就是Integer;name,code字段为varchar,对应的javaType就是String。
在调用接口获得返回值后还需要转换为对应类型。
2.定义一个resultMap标签,
在resultMap的type属性指定type="java.util.Map";
例如:
MapgetRoleInfo(@Param("userId")Integer id);
这种情况Map中的value返回值类型在resultMap中通过javaType指定了,在调用接口获得返回值后可以直接使用。
3.返回的Map对象
第一列数据作为key,第二列数据作为value,跟列名就没关系了。
需要用到ResultHandler,ResultHandler主要作用是用来做数据转换的,这里不详细展开。
定义一个MapResultHandler
public class MapResultHandlerimplements ResultHandler
mapper中定义的方法设置返回值为void
public interface AllMedicalRecordStatisticsMapper extends BaseMapper{ void queryAllAverageScoreList(@Param("params") List params, MapResultHandler mapResultHandler); void queryFirstRateRecordList(@Param("params") List params, MapResultHandler mapResultHandler); }
service调用时new一个自定义的MapResultHandler
public MapqueryAllAverageScoreList(List params) { MapResultHandler resultHandler = new MapResultHandler<>(); allMedicalRecordStatisticsMapper.queryAllAverageScoreList(params,resultHandler); return resultHandler.getMappedResults(); }
xml中定义一个对应的resultMap
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。