在MyBatis(而不是List)中返回结果的HashMap

时间:2016-07-04 14:41:48

标签: mybatis

MyBatis可以返回结果的HashMap,而不是List吗? 例如给出一张表:

APXS = os.environ.get('APXS')

WITH_HTTPD_PACKAGE = False

if APXS is None:
    APXS = find_program(['mod_wsgi-apxs'],
            paths=[os.path.dirname(sys.executable)])
    if APXS is not None:
        WITH_HTTPD_PACKAGE = True

if APXS is None:
    APXS = find_program(['mod_wsgi-apxs', 'apxs2', 'apxs'],
            'apxs', ['/usr/sbin', os.getcwd()])
elif not os.path.isabs(APXS):
    APXS = find_program([APXS], APXS, ['/usr/sbin', os.getcwd()])

if not WITH_TARBALL_PACKAGE:
    if not os.path.isabs(APXS) or not os.access(APXS, os.X_OK):
        raise RuntimeError('The %r command appears not to be installed or '
                'is not executable. Please check the list of prerequisites '
                'in the documentation for this package and install any '
                'missing Apache httpd server packages.' % APXS)

和查询

foo  | bar
 1   |  a
 2   |  b

返回SELECT foo, bar FROM foobar HashMap<String, String> mapmap.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>

如果表具有主键,那么能够将结果作为PK =&gt;的映射更有用。行,而不仅仅是行列表。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:-2)

使用如下所示,您的多个结果将毫无问题地处理。

// 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);