How to get a sorted result in iBatis?
I have a table mgr_employee with 2 columns managerName, teamEmployee.
Although I do a sort in sql I get unsorted resultMap in java. How can I get a sorted map? Why does iBatis开发者_开发百科 mix up the resultMap?<resultMap id="s_filter_defaults_ResultMap" class="java.util.HashMap">
<result property="key" column="managerName"/>
<result property="value" column="count"/>
</resultMap>
<select id="mCount" parameterClass="java.util.HashMap" resultMap="mcount_ResultMap">
<![CDATA[
select managerName, count(teamEmployee) AS count
from mgr_employee
group by managerName
order by managerName;
]]>
</select>
Java code to call the above sql:
Map<String,Long> mCountMap = getSqlMapClientTemplate().queryForMap("mCount", "", "key", "value");
mCountMap is not sorted as was expected due to the "order by" clause in the sql. Any comments/suggestion, how to get the resultMap sorted?
I think your problem might be with the Java types used. To need to query for a list, not for a Map, because the Java HashMap (I suppose this is what the query will return) doesn't have support for sorting. See the SqlMapDaoTemplate#queryForList() methods that should return what you need.
I think your problem is due to the fact that the Map is not an ordered structure: the keys of the map are stored in the order of their hash codes. What you would need to do is to put the keys of the map into a vector and then sort them (or have SQL sort them for you and then insert them into a vector). Then you could iterate over vector and access the map by the keys.
A java.util.LinkedHashMap
will ensure iteration in the order that items were added, try using that class instead of just a plain HashMap
, which does not maintain iteration order.
精彩评论