Mybatis结果为Map <integer,list <integer =“”>&gt;

时间:2016-10-24 08:02:33

标签: postgresql mybatis

我有一个循环查询,它以

的形式获取结果
 id | dependencies 
----+--------------
  1 | {1,2,3,4,5}
  2 | {2,3,4,5}
  3 | {3,4,5}
  4 | {4,5}
  5 | {5}
(5 rows)

我需要将此数据映射到

HashMap<Integer, List<Integer>>,
where
column "id" becomes KEY
column "dependencies" becomes VALUE
(dependencies= postgres array obtained after array_agg)

显然,结果集映射为

@Results(value={

            @Result(column="id", property="key", javaType=Integer.class),
            @Result(column="dependencies", property="value", typeHandler=ArrayTypeHandler.class)
    })


Im getting the results with  return type as
List<Map<Integer, List<Integer>>>, but they are not as expected

有没有办法可以将结果直接映射到地图中?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用ResultHandler:

// declared as "final" to be visible in the anonymous class scope
final Map<Integer, String> result = new HashMap<Integer, String>();

ResultHandler resultHandler = new ResultHandler() {
    @Override
    public void handleResult(ResultContext resultContext) {
        Map object = (Map) resultContext.getResultObject();
            result.put((Integer)object.get("id"), (String)object.get("dependencies"));
        }
    };

session.select("myStatement", resultHandler);
LOGGER.info(result);

您也可以通过mapper界面执行此操作:

// declare in mapper interface
@ResultType(value=Map.class)
@Results(value={
        @Result(column="id", property="id", javaType=Integer.class),
        @Result(column="dependencies", property="dependencies", typeHandler=ArrayTypeHandler.class)
})
void myStatement(ResultHandler resultHandler);

// call
session.getMapper(MyMapper.class).myStatement(resultHandler);

您必须将 @ResultType 指定为Map, 或引用 @ResultMap(&#34; myResultMap&#34;),其映射在XML中定义,然后删除 @Results 。 否则抛出BindingException:

  

方法myStatement需要一个@ResultMap注释,一个@ResultType   注释,或XML中的resultType属性,因此ResultHandler可以   用作参数。