SoFunction
Updated on 2025-03-08

Java MyBatis returns two fields as the key and value of Map

Java MyBatis returns two fields as the key and value of the Map

This may occur when using MyBatis:

To query only two fields, you need to return a Map, where the first field is the key and the second field is the value.

This kind of query is very useful in some scenarios, such as querying dictionary, the query key and value are the value and label of the dictionary. Using the HashMap get method, the time complexity of the time is O(1), can realize the rapid mapping of the dictionary.

The writing method is very particular at this time

Return to Map directly:

When the data volume exceeds 1, an error will be reported. Because Map is used as an object at this time, an object cannot store multiple contents.

Plus<font style="color:rgb(77, 77, 77);">@MapKey</font>annotation:

It is necessary to specify which field to be returned as the key. Although a map can be generated, the value in it is an object, not a direct value, and does not match the expectations.

To achieve the expected return value, you need to use the provided by MyBatisResultHandlerResult processor.

1. Customize a Map result processor

<font style="color:#080808;background-color:#ffffff;">MapResultHandler</font>
public class MapResultHandler<K,V> implements ResultHandler<Map<K,V>> {
    
    private final Map<K,V> mappedResults = new HashMap<>();

    @Override
    public void handleResult(ResultContext context) {
        Map map = (Map) ();
        ((K)("key"), (V)("value"));
    }

    public Map<K,V> getMappedResults() {
        return mappedResults;
    }
}

2. Write

void selectMap(MapResultHandler<String, String> mapResultHandler);

If you want to pass parameters, specify them first, for example:

void selectMap(@Param("type") String type, MapResultHandler<String, String> mapResultHandler);

3. Write

<resultMap  type="">
    <result property="key" column="value"/>
    <result property="value" column="label"/>
</resultMap>

<select  resultMap="mapResult">
    SELECT
        t1.`value`,
        t1.`label`
    FROM
        sys_dict t1
    WHERE
        t1.`type` = #{type}
        AND t1.`del_flag` = '0'
</select>

4. Call

MapResultHandler<String, String> resultHandler = new MapResultHandler<>();
((), resultHandler);
Map<String, String> map = ();

The Map obtained in this way uses two fields as the key and value of the Map.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.