Search code examples
javadatamapperibatis

Retrieve Key-Value Pairs as Map


I'm trying to retrieve two columns from the DB with iBatis. I want to do it as a Map, such that resultMap.get(col1) == col2Obj.

The same question was asked here, but the posted solution won't work for me, and fails with the error: Cannot cast List as Map. I am using iBatis 2.3.4. (Is this feature available in this version? I can't seem to find the relevant documentation.)

My statement map:

<resultMap id="countMap" class="java.util.HashMap">
    <result property="key" column="KEY" />
    <result property="value" column="VALUE" />
</resultMap>
<select id="getCounts" resultMap="countMap" parameterClass="map">
SELECT
    TYPE AS KEY,
    SUM(VAL) AS VALUE
FROM MYTABLE
WHERE REGDATE BETWEEN #start_date# and #end_date#
GROUP BY TYPE
</select>

The actual query returns:

|| KEY || VALUE ||
|| 4   || 304   ||

Calling .toString() on the Map that returns:

{"key" : "4", "value" : "304" }

Since the keyset consists of {"key", "value"}, the resultMap doesn't appear to be doing what I want it to do. When I call the query with parameters that would result in more than 1 row, I get the error.

I am using sqlMapClient.queryForMap("mymap.getCounts", args); to execute the query.


Solution

  • Wups, I got it.

    I needed to use

    sqlMapClient.queryForMap("mymap.getCounts", args, "key", "value");