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>
相关推荐
tycooncool4 小时前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis
一只大袋鼠18 小时前
MyBatis 入门详细实战教程(一):从环境搭建到查询运行
java·开发语言·数据库·mysql·mybatis
Full Stack Developme1 天前
MyBatis-Plus 流式查询教程
前端·python·mybatis
ccice011 天前
全面掌握Spring Boot + MyBatis + Maven + MySQL:从开发到部署的后端技术详解
spring boot·maven·mybatis
消失的旧时光-19431 天前
Spring Boot + MyBatis 从 0 到 1 跑通查询接口(含全部踩坑)
spring boot·后端·spring·mybatis
1.14(java)1 天前
MyBatis 操作数据库
数据库·mybatis
杰克尼2 天前
天机学堂项目总结(day1~day2)
大数据·jvm·spring·elasticsearch·搜索引擎·spring cloud·mybatis
Java成神之路-2 天前
SpringBoot 整合 SSM 全流程详解(含 JUnit+MyBatis 实战)(Spring系列18)
spring boot·junit·mybatis
时间静止不是简史2 天前
当MyBatis-Plus的like遇上SQL通配符:下划线翻车记
java·sql·mybatis
夕除2 天前
javaweb--10
mybatis