您的位置:首页 > 其它

mybatis学习之查询结果返回List以及Map

2017-07-09 00:30 567 查看
当要查询的结果不是单个记录而是一个集合的时候,mybatis的resultType写的依然是集合中的对象的类型名称,例如:

<select id="getPersonByNameLike"resultType="mybatis_01.Person">
select * from person where name like #{name}
</select>


该模糊查询查出的是一个List集合,但是resultType写的是集合中元素的类型

将查询结果封装成Map的两种情况:

1.若查询的结果是单条记录,采用如下的方式:

<select id="getPersonByIdReturnMap" resultType="map">
select * from person where id=#{id};
</select>


注意,此时的resultType写的是map,这是以为mybatis为这些集合起了别名

2.若查询的结果是多条记录时,要将每条记录都封装成Map,需要使用以下方式:

<select id="getPersonByNameLikeReturnMap" resultType="mybatis_01.Person">
select * from person where name like #{name};
</select>


此时resultType是Map中value的类型,使用注解方式指定Map的key

@MapKey

@MapKey("id")
public Map<Integer, Person> getPersonByNameLikeReturnMap(String name);


以上的方法返回的Map的key就是Person的id,Value就是这个Person对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis