@MapKey----mybatis返回Map

mybatis返回Map

有时候我们可能想让一条查询语句直接能够返回Map,而不是List。

可以使用@MapKey来指定实体类中让哪个属性来当key(注意是实体类中的属性,不是表中的字段),而value就是所需的对象。

实体类:People,该实体类不一定是与数据库表对应的
@Data
@TableName("people")
public class People implements Serializable {
     

    private static final long serialVersionUID = 1L;

    @TableId("id")
    private Integer id;

    @TableField("name")
    private String name;

    @TableField("address")
    private String address;

    @TableField("phone")
    private Long phone;
}
mapper里:
public interface PeopleMapper extends BaseMapper<People> {
     

    //这个name是People中的属性,而不是表中的字段
    @MapKey("name")
    Map<String,People> getAllPeople();
}
xml中:
   <select id="getAllPeople" resultType="java.util.Map" resultMap="peopleResultMap">
        select id, `name`, address, phone
        from people
    select>

    <resultMap id="peopleResultMap" type="com.springlearn.qiyan.mapkey.entity.People">
        <result property="name" column="name"/>
        <result property="phone" column="phone"/>
        <result property="address" column="address"/>
    resultMap>

在xml中应该写好该类对应的resultMap

表中数据

@MapKey----mybatis返回Map_第1张图片

返回值:
{
     
    "code": 200,
    "msg": "处理成功",
    "data": {
     
        "陆游": {
     
            "id": 4,
            "name": "陆游",
            "address": "北京",
            "phone": 13954687412
        },
        "辛弃疾": {
     
            "id": 3,
            "name": "辛弃疾",
            "address": "济南",
            "phone": 12574693258
        },
        "李白": {
     
            "id": 1,
            "name": "李白",
            "address": "成都",
            "phone": 13469521374
        },
        "韩信": {
     
            "id": 2,
            "name": "韩信",
            "address": "山东",
            "phone": 19634895213
        },
        "苏轼": {
     
            "id": 5,
            "name": "苏轼",
            "address": "苏州",
            "phone": 13697532169
        }
    }
}

你可能感兴趣的:(java,java,mybatis)