浅析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<Integer, StudentDO> groupById();

<select id="groupById" resultType="StudentDO">
    select * from student
</select>

  即可达到上面的效果。

三、返回List<Map<K,V>> 结构类型数据

// dao层
List<Map<String, Object>> selectInviteRank();
// xml
<select id="selectInviteRank" resultMap="TestMap">
</select>

<resultMap id="TestMap" type="java.util.HashMap">
  <result column="userId" property="test1"></result>
  <result column="invites" property="invites"></result>
  <result column="account" property="account"></result>
  <result column="headImgUrl" property="headImgUrl"></result>
</resultMap>

  需要注意的是 userId 转为了 test1,createdTime 的驼峰,如果没在 resuleMap 里加的话,会变成小写。

posted @ 2022-03-21 21:49  古兰精  阅读(15842)  评论(1编辑  收藏  举报