故事的發生是這樣的. . . . . . .
一天 我發現我們的頁面顯示了這樣的匯總統計數據,看起來體驗還不錯哦~~
然后,我發現代碼是這樣滴:分開每個狀態分別去查詢數量。
額e,可是為嘛不使用簡單便捷的 group by 語句呢
我們知道MyBatis提供了selectMap的方法,查詢結果為hashmap。查詢的時候,可以配置相應的傳入參數和查詢返回結果。
對應dao 層代碼如下:
//查詢各狀態對應的數量,三個參數分別對應,select的id,查詢參數,返回hashmap的key
public Map<String, Map<String,Integer>> sumStatusByParam(SearchParam searchParam ){ return (Map<String, Map<String,Integer>>)sqlSessionTemplate.selectMap(SEARCH_NAME_SPACE + "sumStatusByParam",searchParam,"status"); }
對應mybatis的數據查詢語句:
<!-- 查詢各狀態對應的數量 -->
<select id="sumStatusByParam" parameterType="com.selicoco.model.dto.param.SearchParam" resultType="hashmap">
select status as status,count(id) as num from selicoco_order where 1=1
<if test="name != null" >
and name like concat('%',#{name,jdbcType=VARCHAR},'%') </if>
group by status; </select>
</mapper>
最后得到的結果是這樣的。
我以為這樣就可以了,但是,count(1)這樣出來的結果是一個Long類型,並不能直接轉換成Integer,雖然查詢的時候並沒有報錯,但是讀取的時候一定會告訴你轉換失敗的,
所以我只能默默的把map里面的 Integer轉換成Long類型。
對於這樣的結果,我們如果要獲取的話,得這樣去取
map.get("WAIT_CONFIRM").get("num");
這樣其實是比較費力的。明白其中的原理其實可以寫一個公用的中間層方法,將里面的map轉換出來。因為我的狀態並不多,所以直接就使用上面的方式去取值了。
selectMap實現機制:
selectMap調用selectList進行查詢,返回一個List<hashMap>,mybatis底層查詢返回其實都是hashMap。
然后再從map里面取出我們指定的key值,放入一個map<key,value>,而value就是底層查詢出來的整個hashmap的值。
源碼如下:
public Map selectMap(String statement, String mapKey) { return selectMap(statement, null, mapKey, RowBounds.DEFAULT); } public Map selectMap(String statement, Object parameter, String mapKey) { return selectMap(statement, parameter, mapKey, RowBounds.DEFAULT); } public Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { final List list = selectList(statement, parameter, rowBounds); final DefaultMapResultHandler mapResultHandler = new DefaultMapResultHandler(mapKey); final DefaultResultContext context = new DefaultResultContext(); for (Object o : list) { context.nextResultObject(o); mapResultHandler.handleResult(context); } return mapResultHandler.getMappedResults(); } public List selectList(String statement) { return selectList(statement, null); } public List selectList(String statement, Object parameter) { return selectList(statement, parameter, RowBounds.DEFAULT); } public List selectList(String statement, Object parameter, RowBounds rowBounds) { try { MappedStatement ms = configuration.getMappedStatement(statement); return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } }
public DefaultMapResultHandler(String mapKey) { this.mapKey = mapKey; } public void handleResult(ResultContext context) { final Object value = context.getResultObject(); final MetaObject mo = MetaObject.forObject(value); final Object key = mo.getValue(mapKey); mappedResults.put(key, value); }
想要返回一個對象可以參考:http://www.denghuafeng.com/post-238.html