如何在 iBatis 中获得排序结果?
我有一个包含 2 列 managerName、teamEmployee 的表 mgr_employee。
虽然我在 sql 中进行了排序,但我在 java 中得到了未排序的 resultMap。
如何获得排序后的映射?为什么 iBatis 会混淆 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>
调用上述 sql 的 Java 代码:
Map<String,Long> mCountMap = getSqlMapClientTemplate().queryForMap("mCount", "", "key", "value");
由于 sql 中的“order by”子句,mCountMap 未按预期排序。 有任何意见/建议,如何对 resultMap 进行排序?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您的问题可能与使用的 Java 类型有关。需要查询列表,而不是Map,因为Java HashMap(我想这就是查询将返回的内容)不支持排序。
请参阅SqlMapDaoTemplate#queryForList()< /a> 应该返回您需要的内容的方法。
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.
我认为你的问题是由于映射不是有序结构:映射的键按照哈希码的顺序存储。您需要做的是将映射的键放入向量中,然后对它们进行排序(或者让 SQL 为您对它们进行排序,然后将它们插入向量中)。然后您可以迭代向量并通过键访问地图。
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.
java.util.LinkedHashMap< /code>
将确保按照添加项目的顺序进行迭代,请尝试使用该类,而不仅仅是一个普通的
HashMap
,它不维护迭代顺序。A
java.util.LinkedHashMap
will ensure iteration in the order that items were added, try using that class instead of just a plainHashMap
, which does not maintain iteration order.