Reputation: 175
I am new to MyBatis. Could anyone help me to resolve this. Thank you.
I created a table named "CodeValue" with columns like "Code","Value" etc. I am retrieving the columns "Code","Value" from the table using mybatis selectMap() method which should return HashMap with key "Code" and value "Value" as follows
<select id="getResults" parameterType="java.util.Map" resultType="java.util.HashMap">
select "Code","Value" from "CodeValue"
</select
Map<String, String> CodeValueMap = getSqlSession().selectMap("getResults", null, "Code");
I defined POJO as below
class CodeValue
{
private String code;
private String value;
....
...
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getKey() {
return "code";
}
public String getDefaultSortColumn() {
return code;
}
public String getUniqueKey() {
return code;
}
...
...
...
}
when I run the code I am getting results like below
{CODE1={Value=A, Code=CODE1}, CODE2={Value=B, Code=CODE2}, CODE3={Value=C, Code=CODE3}, CODE4={Value=D, Code=CODE4}, CODE5={Value=E, Code=CODE5}, CODE6={Value=F, Code=CODE6}, CODE7={Value=G, Code=CODE7}}
but I want results as follows
{{CODE1=A},{CODE2=B},{CODE3=C},{CODE4=D},{CODE5=E},{CODE6=F},{CODE7=G}
Thank You
Upvotes: 0
Views: 1491
Reputation: 3594
MyBatis may not be able to return a Map
directly in the form you need.
But it is not so hard to convert the result.
If you call selectList()
[1], MyBatis may return a list of Map
s.
[{Value=A, Code=CODE1},
{Value=B, Code=CODE2},
{Value=C, Code=CODE3}]
And the below is an example code that performs the conversion.
List<Map<String, Object>> maps = sqlSession.selectList("getResults");
Map<String, String> map = maps.stream()
.collect(Collectors.toMap(
m -> (String) m.get("CODE"),
m -> (String) m.get("VALUE")));
assertEquals("A", map.get("Code1"));
assertEquals("B", map.get("Code2"));
assertEquals("C", map.get("Code3"));
[1] selectMap()
is a method for very specific usage.
Upvotes: 1