mybatis group by查詢返回map型別

2022-08-11 04:57:06 字數 2083 閱讀 9726

故事的發生是這樣的. . . . . . .

一天 我發現我們的頁面顯示了這樣的匯**計資料,看起來體驗還不錯哦~~

然後,我發現**是這樣滴:分開每個狀態分別去查詢數量。

額e,可是為嘛不使用簡單便捷的 group by 語句呢

我們知道mybatis提供了selectmap的方法,查詢結果為hashmap。查詢的時候,可以配置相應的傳入引數和查詢返回結果。

對應dao 層**如下:

//

查詢各狀態對應的數量,三個引數分別對應,select的id,查詢引數,返回hashmap的key

public map>sumstatusbyparam(searchparam searchparam )

對應mybatis的資料查詢語句:

<

select id="sumstatusbyparam" parametertype="com.selicoco.model.dto.param.searchparam" resulttype="hashmap">

select status as status,count(id) as

num

from

selicoco_order

where1=

1<

if test="name !=

null" >

and name like concat('

%',#,'%'

)

if>

group

bystatus;

select

>

最後得到的結果是這樣的。

我以為這樣就可以了,但是,count(1)這樣出來的結果是乙個long型別,並不能直接轉換成integer,雖然查詢的時候並沒有報錯,但是讀取的時候一定會告訴你轉換失敗的,

所以我只能默默的把map裡面的 integer轉換成long型別。

對於這樣的結果,我們如果要獲取的話,得這樣去取

map.get("wait_confirm").get("num");

這樣其實是比較費力的。明白其中的原理其實可以寫乙個公用的中間層方法,將裡面的map轉換出來。因為我的狀態並不多,所以直接就使用上面的方式去取值了。

selectmap實現機制:

selectmap呼叫selectlist進行查詢,返回乙個list,mybatis底層查詢返回其實都是hashmap。

然後再從map裡面取出我們指定的key值,放入乙個map,而value就是底層查詢出來的整個hashmap的值。

原始碼如下:

public

map selectmap(string statement, string mapkey)

public

map selectmap(string statement, object parameter, string mapkey)

public

map selectmap(string statement, object parameter, string mapkey, rowbounds rowbounds)

return }

public

list selectlist(string statement)

public

list selectlist(string statement, object parameter)

public

list selectlist(string statement, object parameter, rowbounds rowbounds)

catch

(exception e)

finally

}

public

defaultmapresulthandler(string mapkey)

public

void

handleresult(resultcontext context)

想要返回乙個物件可以參考:

Spring data jpa多表查多條件查詢

現有如下場景,需要根據a表的check code欄位和b表的store code check result欄位組合查詢,a表與b表的關聯關係為一對多。為了簡化查詢引數,我們對查詢引數進行了封裝,抽出了公共的querycondition public class querycondition publ...

並查集 並查集

本文參考了 挑戰程式設計競賽 和jennica的github題解 陣列版 int parent max n int rank max n void init int n int find int x else void union int x,int y else 結構體版 struct node ...

並查集入門(普通並查集 帶刪除並查集 關係並查集)

什麼是並查集?通俗易懂的並查集詳解 普通並查集 基礎並查集 例題 題解 how many tables problem description lh boy無聊的時候很喜歡數螞蟻,而且,還給每乙隻小螞蟻編號,通過他長期的觀察和記錄,發現編號為i的螞蟻會和編號為j的螞蟻在一起。現在問題來了,他現在只有...