2016-07-04 93 views
1

MyBatis可以返回结果的HashMap而不是List? 例如给定一个表:在MyBatis(而不是List)中返回结果的HashMap

foo | bar 
1 | a 
2 | b 

和查询

SELECT foo, bar FROM foobar 

回报HashMap<String, String> map结果,其中map.get(1) == 'a'map.get(2) == 'b'等?

我试过的变化在以下方面:

<resultMap id="hashMapResult" type="java.util.HashMap"> 
     <id column="foo" /> 
     <result property="bar" column="bar"/> 
    </resultMap> 

    <select id="personStatuses" resultMap="hashMapResult"> 
     SELECT foo, bar FROM foobar 
    </select> 

但是,仅仅得到错误:Expected one result (or null) to be returned by selectOne(), but found: ...

如果表有主键,这将是能够得到的结果更有用一个PK =>行的Map,而不仅仅是一个行列表。

回答

1

你必须要透视表,让列foo的行作为列,Mybatis不能做到这一点,但您可以使用SQL来实现这一点(这里是一个mysql溶液):

select 
    max(case when foo = 1, then bar else null end) as `1`, 
    max(case when foo = 2, then bar else null end) as `2` 
from foobar; 
0

使用像下面一样,你的多个结果将被处理,没有任何问题。

// in your mapper XML 
<select id="personStatuses" resultType="java.util.HashMap" > 
     SELECT foo, bar FROM foobar 
</select> 

// From Java code - list of hashmaps 
List<HashMap> personStatuses = yourMyBatisDao.personStatuses(); 

sysout(personStatuses); 
+0

这只是返回一个像正常的List,而不是PK =>行的HashMap – Mark

相关问题