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>
相关推荐
打死不学Java代码2 小时前
PaginationInnerInterceptor使用(Mybatis-plus分页)
android·java·mybatis
Code哈哈笑8 小时前
【Spring Boot】深入解析:#{} 和 ${}
java·spring boot·后端·spring·mybatis
quququ_213810 小时前
Java面试:从Spring Boot到微服务的全面考核
spring boot·微服务·kubernetes·mybatis·hibernate·java面试
BillKu19 小时前
Spring Boot + MyBatis 动态字段更新方法
java·spring boot·mybatis
我家领养了个白胖胖1 天前
#和$符号使用场景 注意事项
java·后端·mybatis
论迹1 天前
【JavaEE】-- MyBatis操作数据库(1)
java·开发语言·数据库·java-ee·mybatis
述雾学java1 天前
Mybatis延迟加载、懒加载、二级缓存
mybatis·java核心基础
红豆和绿豆2 天前
mybatis-plus开发orm
java·开发语言·mybatis
Java&Develop2 天前
Spring Boot+Mybatis设置sql日志打印
spring boot·sql·mybatis
安清h2 天前
【基于SprintBoot+Mybatis+Mysql】电脑商城项目之显示勾选的购物车数据和创建订单
数据库·spring boot·后端·mysql·mybatis