Mybatis @MapKey注解实现List转Map

文章目录


@MapKey介绍

在MyBatis中,@MapKey 主要用于在映射查询结果到一个Map。

当你执行一个查询并期望返回一个Map时,你可以使用@MapKey来进行结果集的映射。而Mybatis内部会将查询到的结果映射为一个key-value的形式。

@MapKey示例

有这么一个场景,需要查询用户列表,并转为Map,map的key为用户ID。

User类:

java 复制代码
@Data
@TableName("sys_user")
public class User implements Serializable {
    private static final long serialVersionUID = -6525322309638123441L;

    @PropIgnore
    @TableId(type = IdType.AUTO)
    private Integer userId;

    private String userName;

    private String password;

    private String salt;

    private String phone;

    private String sex;

    private String email;

    private String nickName;

    private String address;

    private Date createTime;

    private Date updateTime;
}

- 传统的写法

Controller:

java 复制代码
    @ApiOperation(value="@MapKey获取用户列表",notes="@MapKey获取用户列表")
    @GetMapping("getUsers")
    public void getUsers() {
        List<User> userList = userMapper.getUsers();
        Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, user -> user, (v1, v2) -> v1));
    }

Mapper:

java 复制代码
List<User> getUsers();

Mapper.xml:

java 复制代码
    <select id="getUsers" resultType="com.joker.pojo.User">
        select * from sys_user limit 100
    </select>

- @MapKey的写法

Controller:

java 复制代码
    @ApiOperation(value="@MapKey获取用户列表",notes="@MapKey获取用户列表")
    @GetMapping("getUsers")
    public void getUsers() {
        Map<Integer, User> userMap = userMapper.getUserIdMapUsers();
    }

Mapper:

java 复制代码
	@MapKey("userId")
    Map<Integer, User> getUserIdMapUsers();

注意:userId为User类的字段名称,而非数据库表的字段名称

Mapper.xml:

java 复制代码
    <select id="getUserIdMapUsers" resultType="com.joker.pojo.User">
        select * from sys_user limit 100
    </select>
相关推荐
敲个大西瓜5 小时前
mybatis拦截器插件实现数据库字段加解密
mybatis
武子康8 小时前
Java-28 深入浅出 Spring 实现简易Ioc-04 在上节的业务下手动实现AOP
java·后端·mybatis
一条泥憨鱼9 小时前
苍穹外卖【day6|微信登录与商品浏览功能】
后端·mybatis·苍穹外卖
vx-Biye_Design9 小时前
springboot安阳地区研学旅游服务小程序-计算机毕业设计源码12785
java·vue.js·windows·spring boot·tomcat·maven·mybatis
摇滚侠10 小时前
MyBatis+Spring+SpringMVC SSM 整合 179-185
java·spring·mybatis
摇滚侠10 小时前
MyBatis+Spring+SpringMVC SSM ContextLoaderListener 177-178
java·spring·mybatis
Spring小子1 天前
【Spring Boot + Vue + DeepSeek】从零打造一个AI驱动的智能健康分析系统
java·spring boot·mybatis
武子康1 天前
Java-27 深入浅出 Spring - 实现简易Ioc-03 在上节的业务下手动实现IoC 从 XML 配置到 BeanFactory 反射注入
java·后端·mybatis
柏舟飞流1 天前
Spring Boot 进阶实战:整合 MyBatis、Redis、JWT,搭一个更像真实项目的后端服务
spring boot·redis·mybatis
z_鑫1 天前
深入理解MyBatis:collection集合封装的底层原理与实现细节
java·开发语言·数据库·spring boot·mybatis