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

Using annotations in mybatis, can we return the type as a 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 he gives below exceptions

 ### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'a' in 'class java.lang.String' 
+6
source share
3 answers

Here's how I do it, without the extra method of converting a list to a map:

Here is the message class

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

Chart maker

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

Unfortunately, it is not possible to create a Map <String, String>

+7
source

@Select("select a, b from tableA") annotation @Select("select a, b from tableA") will return a list of maps, where each map will contain one record. You can write a converter for it.

 public Map<Object,Object> mapFromListOfMap (List<Map> listOfMap ) { Map<Object,Object> map = new HashMap<Object,Object>(); for(int i = 0; i < listOfMap.size(); i++) { Object key = (Object) listOfMap.get(i).get("a"); Object value = (Object)listOfMap.get(i).get("b"); map.put(key, value); } return map; } 

@Select("select a, b from tableA") will return something like this

 List[0] -> Map ((key=>'a',value=>1),((key=>'b',value=>'a'))) List[1] -> Map ((key=>'a',value=>2),((key=>'b',value=>'b'))) List[2] -> Map ((key=>'a',value=>3),((key=>'b',value=>'c'))) 

and the mapFromListOfMap function will do something like this

 Map ((key=>'1',value=>'a'),(key=>'2',value=>'b'),(key=>'3',value=>'c')) 

hope this helps :)

+5
source

@MapKey (a) will return a map with your results using

EDIT: Interesting result. Did not try to use annotations (use mappers instead), but AFAIK looks like it expects a HashMap<someA, someB> , where someA has a getter and setter for "a" (for example, getA, setA) ... you you can even use the same class (HashMap

+1
source

Source: https://habr.com/ru/post/908078/


All Articles