How to get Map<String, String> as return type using mybatis annotations

Mohit Verma picture Mohit Verma · Feb 9, 2012 · Viewed 26.1k times · Source

Using annotations in mybatis, can we have return type as normal map ?

Basically, I want something like this

@Select("select a, b from tableA")
public Map<String, String> getItems();

Where

mysql> select * from tableA;
+------+------+
| a    | b    |
+------+------+
| 1    | a    |
| 2    | b    |
| 3    | c    |
+------+------+

mysql> desc tableA;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| a     | varchar(10) | YES  |     | NULL    |       |
| b     | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

Tried this

@Select("select a, b from tableA")
@MapKey("a)
public Map<String, String> getItems();

but it's giving below exception

### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'a' in 'class java.lang.String'

Answer

Dmitry Sergeev picture Dmitry Sergeev · Apr 15, 2013

Here is how i do this, without extra method for converting List to Map:

Here is Message class

public class Message {
   private String code;
   private String message;
   GETTERS/SETTERS
}

Mapper

@Select("SELECT code, message FROM MESSAGES")
@MapKey("code")
public Map<String, Message> selectAllMessages();

Unfortunatly it's impossible to create Map<String, String>