問題描述:瀏覽器頁面想要通過E-hcart表格,展示一些數據。這些數據需要從數據庫中計算而來。但是在數據庫中沒有的字段。比如說要查詢某些記錄。如車輛的在線數量,離線數量和無數據的數量。這些數據是通過MySql的聚合函數得到的。
sql語句如下:
SELECT
sum(
updatetime > date_sub(now(), INTERVAL 0.5 DAY)
) AS online,
sum(updatetime IS NULL) nodata,
count(1) - sum(
updatetime > date_sub(now(), INTERVAL 0.5 DAY)
) - sum(updatetime IS NULL) AS offline
,COUNT(1)
FROM
cx_onecdata
WHERE
kdgs = '順豐'
AND cartype LIKE '%gps%'
查詢的結果如上圖。
注意,這些統計的字段都是數據庫中沒有的。
那麼問題來了,該如何獲取這些數據呢?
問題的解決方法:在MyBaits中生成相對應的字段。比如,我的實體類中是這樣的(也就是DO):
public class Sfcar {
private Integer online;
private Integer nodata;
private Integer offline;
public Integer getOnline() {
return online;
}
public void setOnline(Integer online) {
this.online = online;
}
public Integer getNodata() {
return nodata;
}
public void setNodata(Integer nodata) {
this.nodata = nodata;
}
public Integer getOffline() {
return offline;
}
public void setOffline(Integer offline) {
this.offline = offline;
}
MyBatis中對應的映射文件是這樣配置的:
<!-- GPS 車輛統計 -->
<select id="findbySFCarGPS" resultMap="BaseResultMap">
SELECT
sum(
updatetime > date_sub(now(), INTERVAL 0.5 DAY)
) AS online,
sum(updatetime IS NULL) nodata,
count(1) - sum(
updatetime > date_sub(now(), INTERVAL 0.5 DAY)
) - sum(updatetime IS NULL) AS offline
FROM
cx_onecdata
WHERE
kdgs = '順豐'
AND cartype LIKE '%gps%'
</select>
這裏有兩個注意的點。一是:返回結果類型是resultMap=”BaseResultMap”。二,MyBatis是跟實體類映射,而不是跟數據庫對應的表映射,所以可以直接寫想要的Sql。最好用這個Do 來接收想要的數據。
至此,可以完美解決字段不對應的問題。
最後頁面顯示的效果:
數據通過渲染得到想要的效果。
說明一下:以前數據中獲取不對應的字段時,我是用List集合裏面放Map集合,獲取所要的數據。
,用來解碼的代碼如:
List<String> legend = new ArrayList<String>();
List<Map> serisData=new ArrayList<Map>();
List<TreeMap<String,Integer>> data = car_Service.selectCarTypeCount();
int count = 0;
List<String> car_typename= new ArrayList<String>();
List<String> car_typevalue = new ArrayList<String>();
// Map<String,String> mapdata= new HashMap<>();
// 遍歷以Key - Value 形式遍歷
for (Map<String, Integer> map : data){
Map tarMap =new HashMap();
for (Map.Entry<String, Integer> k : map.entrySet()){
count++;
if (count % 2 == 0) {
car_typename.add(k.getValue()+"");
}else{
car_typevalue.add(k.getValue()+"");
}
}
for (int i = 0; i < car_typename.size(); i++) {
// 獲取 List 中的 String 數組元素。
String cartype_name = car_typename.get(i);
String cartype_value = car_typevalue.get(i);
// mapdata.put(cartype_name, cartype_value);
if (i== car_typename.size()-1) {
legend.add(cartype_name);
tarMap.put("value", cartype_value);
tarMap.put("name", cartype_name);
serisData.add(tarMap);
}
}
}
// 縱座標
List<SeriesVO> series = new ArrayList<>();
series.add(new SeriesVO("總數比較", "pie",serisData));
EchartDataVO targetdata = new EchartDataVO(legend,null, series);
// 獲取 目標數據 JSON 格式
return targetdata;
至此問題解決!
《end》