SoFunction
Updated on 2025-04-14

mybatis returns the result as Map problem

mybatis returns the result as Map

surface:membersIn-housegenderThe column is like this:

Female
Female
Male
Female
Male
Male
Male
Male
Male

Now we want to count the number of men and women in members. Obviously, the result returned should be like this:

Femal: 3
Male: 6

Query statements in the corresponding xml file:

<select  resultMap="genderCount">
    select
        gender,
        count(gender) count
    from members
    group by gender
  </select>

<resultMap  type="">
    <result column="gender" property="key" javaType=""/>
    <result column="count" property="value" javaType=""/>
</resultMap>

Question 1

According to the conventional idea, the result returned by mybatis should be a map object, and it contains two entry.

Therefore, the corresponding mapper interface should be sub-:

Map<String, Integer> getGenderCount();

But defining the interface in this way will be abnormal. The roughly means: the query result is either null or there is only one, but now multiple results appear.

Such error message is very obvious, and the mapper interface should be defined as:

List<Map<String, Integer>> getGenderCount();

The query result in the xml file is a list. This list contains two map objects, and each map object contains only one entry.

(It seems to be usedresultHandlerYou can make the return result of a query in xml to include two entry forms in the map object)

Question 2

There are two maps in the list, so what is the entry in each map?

Also according to the conventional idea, the two maps should be: {Femal:3} and {Male:6} respectively.

But the actual return result is:

[
map1:{
	key:Femal,
	value: 3
}
map2:{
	key:Male,
	value: 6
}
]

So it needs to be converted to the type we expect.

In this demo, the mapper interface needs to be defined like this.

List<Map<String, Object>> getGenderCount();

Because the type of value can be String and may be Integer.

Convert the results of List<Map<String, Object>> of the xml query, the code is as follows:

private Map<String, Integer> getMetricsLatestVersion(
      List<Map<String, Object>> genderCountList) {

    Map<String, Integer> genderCount = new HashMap<>();
    for (Map<String, Object> kv : genderCountList) {
      String key = null;
      Integer value = null;

      for (<String, Object> entry : ()) {
        if (().equals("key")) {
          key = (String) ();
        } else {
          value = (Integer) ();
        }
      }
      (key, value);
    }
    return genderCount;
  }

Summarize

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