本文介绍了在 MyBatis 中返回结果的 HashMap(而不是 List)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyBatis 可以返回结果的 HashMap 而不是 List 吗?例如给定一个表格:

Can MyBatis return a HashMap of results, instead of a List?e.g. given a table:

foo  | bar
 1   |  a
 2   |  b

和查询

SELECT foo, bar FROM foobar

返回HashMap的结果;map where map.get(1) == 'a', map.get(2) == 'b' 等等?

Return a result of HashMap<String, String> map where map.get(1) == 'a', map.get(2) == 'b' etc?

我尝试了以下变体:

    <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>

但只是得到错误:预期 selectOne() 返回一个结果(或 null),但发现:...

在表有主键的情况下,能够将结果作为 PK => 行的 Map 而不是仅仅行列表会更有用.

Where tables have primary keys, it would be more useful to be able to get the results as a Map of PK => row, than just a List of rows.

推荐答案

你必须旋转你的表格,让 foo 列的行作为列,Mybatis 不能这样做,但你可以使用 sql 来实现这一点(这里是一个 mysql 解决方案):

You have to pivot your table, let column foo's rows as column, Mybatis can not do this, but you can use sql to achieve this(here is a mysql solution):

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;

这篇关于在 MyBatis 中返回结果的 HashMap(而不是 List)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:31