@MapKey usage instructions

I. Introduction

@MapKey  is an annotation of the MyBatis framework. Its function is to convert the List result set into a Map result set in the form of key-value, which is convenient for quickly querying the specified results from the result set.

insert image description here

1.1. Usage

1.1.1, dao layer

@MapKey("id")
Map getStudents();

1.1.2, xml layer

<!--获取学生基本信息-->
<select id="getStudents" resultType="map">
    SELECT id, idCard, name FROM students
</select>

1.2. Effect

before use

After use

 2. Matters needing attention

2.1. Pay attention to the type of key

It is worth noting that the key type of the Map returned through the @MapKey annotation is consistent with the specified field type.

For example: if you specify id as the key of the Map, and the id is of int type, then the key of the Map is also of type integer. If you use the key of String type to obtain the value, you will not be able to obtain it.

 2.2 、Solution

2.2.1. Keep it as it is

If you don't need to use it externally, you can keep it as it is, just pay attention to the type of key.

2.2.2. Uniformly use String as Key

You can modify the returned data type directly through the mysql function.

<!--获取学生基本信息-->
<select id="getStudents" resultType="map">
    SELECT Cast(id as char) AS id, idCard, name FROM students
</select>

3. Reference articles

@MapKey's blog using _make_888 - CSDN blog _@mapkey

Guess you like

Origin blog.csdn.net/qq_41057885/article/details/125824289