Search code examples
javamybatisibatis

iBatis/MyBatis - Get a Map of result instead of a List with custom keys and values


Here's my code:

<resultMap class="<custom_class>" id="maptoCustomClass">
         <result property="idModifiedBy" column="col2" />
     <result property="assignedTeamName" column="col3" />
      </resultMap>

      <resultMap class="java.util.HashMap" id="resultMapId">
         <result property="key" column="col1"/>
     <result property="value" resultMap="file.maptoCustomClass"/>
      </resultMap>

      <select id="fetchTaskTeamAndUser" parameterClass="java.util.HashMap"  resultMap="resultMapId">
        SELECT col1, col2, col3
        FROM schema_name.table_name
      </select>

This is not working and throwing 'Too many rows returned' error. I understand why.

My question is how can I fetch the results as a KEY and VALUE pair of a HashMap?

e.g. I should get one HashMap with key as the value of col1 and values as the object that contains the values of col2 and col3.


Solution

  • Try as :

    Map<String,Long> mCountMap = getSqlMapClientTemplate().queryForMap("mydata", "", "key", "value");
    
    <resultMap id="hashMapResult" class="java.util.HashMap">
        <result property="key" column="col_1"/>
        <result property="value" column="col_2"/>
    </resultMap>
    
    <select id="mydata" resultMap="hashMapResult">
        select col_1, col_2 from sometable
    </select>