浅析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 @   古兰精  阅读(24923)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2018-03-21 浅析Linux执行可执行文件提示No such file or directory的解决方法
2018-03-21 D3.js系列——布局:打包图和地图
2018-03-21 Vue生命周期总结
2018-03-21 Vue生命周期各阶段发生的事情
点击右上角即可分享
微信分享提示