浅析Mybatis如何返回Map结构、@MapKey()的使用、返回List<Map<K,V>> 结构类型数据
一、Mybatis返回Map结构
// 使用Mybatis返回Map结构时,字段别名需要用双引号包裹否则别名会全部小写,没有驼峰
<select id="selectById" resultType = "map">
select id as "myId",name as "myName" from t_user
select>
// 对象则不用
<select id="selectById" resultType = "xxx.User">
select id as myId,name as myName from t_user
select>
二、@MapKey()的使用
这个注解是作用在方法上面的,具体的用法就是设置外面Map的KEY是什么。这样我们就能够查询出非常复杂的结果,而不用在建立一个新的实体。
希望mybatis返回以下Map格式数据:
{
"100": {
"id": 100,
"name": "小民",
"age": 20
},
"101": {
"id": 101,
"name": "小白",
"age": 20
}
}
@MapKey("id")
Map groupById();
<select id="groupById" resultType="StudentDO">
select * from student
select>
即可达到上面的效果。
三、返回List
// dao层 ListTestMap" type="java.util.HashMap">"userId" property="test1"> "invites" property="invites"> "account" property="account"> "headImgUrl" property="headImgUrl">
需要注意的是 userId 转为了 test1,createdTime 的驼峰,如果没在 resuleMap 里加的话,会变成小写。