![](/img/trans.png)
[英]Understanding the use of @ModelAttribute and @RequestAttribute annotations in Spring MVC
[英]Return HashMap in mybatis and use it as ModelAttribute in spring MVC
我想使用spring mvc @modelAttribute在我的Jsp頁面中顯示類別列表。
在我的mapper.xml文件中
<select id="selectAllCategories" resultMap="BaseResultMap">
select id, name from categories
</select>
在我的Mapper.java類中,我有方法
List<Map<String, String>> selectAllCategories();
我想要一個像這樣的方法:
Map<Integer, String>`selectAllCategories();
而不是List<Map<>>
,這可能嗎?
您想獲取Map<Integer,String>
,其中Integer是id
,String是name
。 如果表中有200個類別,則表示地圖中有200個條目,而不是200個地圖的列表。
MyBatis不能完全開箱即用,但您可以使用它的設施來做到這一點。 我看到兩個選擇。
選項1:
第一個不是你要求的,但值得展示。 它為您提供了Map<Integer,Category>
,其中Category是具有id,name(以及可能來自categories表的其他字段)的categories表的域對象。 創建Category域對象后,使用@MapKey
批注在MyBatis中很容易做到:
@Select("SELECT id, name FROM categories")
@MapKey("id")
Map<Integer,Category> getAllCategories();
在您的代碼中,您將執行以下操作:
MyMapper mapper = session.getMapper(MyMapper.class);
Map<Integer,Category> m = mapper.getAllCategories();
根據您是否可以將名稱提取為Category對象的屬性,這可能適用於您的用例,也可能不適用。
選項2:
要獲取您要求的Map<Integer,String>
,我知道的最簡單的方法是創建一個實現MyBatis ResultHandler接口的類。
您的ResultHandler將使用MyBatis創建的column-name => column-value的默認hashmap,並創建一個主Map。 這是代碼:
public class CategoryResultHandler implements ResultHandler {
Map<Integer,String> inMap = new HashMap<Integer,String>();
public Map<Integer, String> getIdNameMap() {
return inMap;
}
@Override
public void handleResult(ResultContext rc) {
@SuppressWarnings("unchecked")
Map<String,Object> m = (Map<String,Object>)rc.getResultObject();
inMap.put((Integer)getFromMap(m, "id"),
(String)getFromMap(m, "name"));
}
// see note at bottom of answer as to why I include this method
private Object getFromMap(Map<String, Object> map, String key) {
if (map.containsKey(key.toLowerCase())) {
return map.get(key.toLowerCase());
} else {
return map.get(key.toUpperCase());
}
}
}
handleResult方法在類別表中每行調用一次。 您告訴MyBatis使用ResultHandler然后提取您的主映射,如下所示:
CategoryResultHandler rh = new CategoryResultHandler();
session.select("getAllCategories", rh);
Map<Integer,String> m = rh.getIdNameMap();
其中一個應該適合你。
最后幾點說明:
為什么我要包含getFromMap()
輔助方法? 因為您無法始終控制MyBatis返回的散列映射中列名稱的大小寫。 更多細節: mybatis- 3.1.1。 如何覆蓋從mybatis返回的resultmap
我在mybatis-koans的Koan26中有這些解決方案的例子(我根據你的問題添加): https : //github.com/midpeter444/mybatis-koans
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.