浅析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 里加的话,会变成小写。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!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生命周期各阶段发生的事情