之前有做個一個自定義報表的查詢,這里使用的是一個動態的sql拼接,是前端選擇了什么指標就查詢什么信息!(這里的指標是多個表的字段,前端隨便選擇了這些指標,然后后端根據這些指標拼接sql,返回這些指標的數據)。
參數接收DTO

1 /** 2 * 自定義報表 3 */ 4 public class DefinedReportFormDTO { 5 /** 6 * 指標id 7 */ 8 private List<Long> ids; 9 /** 10 * 開始時間 11 */ 12 @DateTimeFormat(pattern = "yyyy-MM") 13 private Date startTime; 14 /** 15 * 結束時間 16 */ 17 @DateTimeFormat(pattern = "yyyy-MM") 18 private Date endTime; 19 /** 20 * 頻率 21 */ 22 private String timeStyle; 23 /** 24 * 機構id 25 */ 26 private List companyIds; 27 28 private boolean avg =false; 29 30 private String idsParam; 31 32 private String companyIdsParam; 33 34 public void setCompanyIdsParam(String companyIdsParam) { 35 this.companyIdsParam = companyIdsParam; 36 } 37 38 public void setIdsParam(String idsParam) { 39 this.idsParam = idsParam; 40 } 41 42 public String getCompanyIdsParam() { 43 return companyIdsParam; 44 } 45 46 public String getIdsParam() { 47 return idsParam; 48 } 49 public boolean isAvg() { 50 return avg; 51 } 52 53 public void setAvg(boolean avg) { 54 this.avg = avg; 55 } 56 57 58 public Date getStartTime() { 59 return startTime; 60 } 61 62 public void setStartTime(Date startTime) { 63 this.startTime = startTime; 64 } 65 66 public Date getEndTime() { 67 return endTime; 68 } 69 70 public void setEndTime(Date endTime) { 71 this.endTime = endTime; 72 } 73 74 public String getTimeStyle() { 75 return timeStyle; 76 } 77 78 public void setTimeStyle(String timeStyle) { 79 this.timeStyle = timeStyle; 80 } 81 82 public List<Long> getIds() { 83 return ids; 84 } 85 86 public void setIds(List<Long> ids) { 87 this.ids = ids; 88 } 89 90 public List getCompanyIds() { 91 return companyIds; 92 } 93 94 public void setCompanyIds(List companyIds) { 95 this.companyIds = companyIds; 96 } 97 98 }
數據返回VO

1 public class DefinedReportFormVO implements Serializable { 2 private String time; 3 private List<Map<String, Object>> arr = new ArrayList<>(); 4 5 public String getTime() { 6 return time; 7 } 8 9 public void setTime(String time) { 10 this.time = time; 11 } 12 13 public List<Map<String, Object>> getArr() { 14 return arr; 15 } 16 17 public void setArr(List<Map<String, Object>> arr) { 18 this.arr = arr; 19 } 20 21 22 }
控制器Controller

1 @GetMapping("/report/defindReport") 2 public JsonResponseExt defindReport(DefinedReportFormDTO definedReportFormDTO){ 3 4 5 6 7 //測試數據 8 9 10 List list1 = new ArrayList<>(); 11 list1.add("111"); 12 definedReportFormDTO.setIds(list1); 13 definedReportFormDTO.setTimeStyle("month"); 14 definedReportFormDTO.setAvg(true); 15 16 17 Calendar instance = Calendar.getInstance(); 18 instance.set(2018,1,11); 19 definedReportFormDTO.setStartTime(instance.getTime()); 20 instance.setTime(new Date()); 21 definedReportFormDTO.setEndTime(instance.getTime()); 22 23 24 return JsonResponseExt.success(dataAcquisitionFileInfoService.defindQuery(definedReportFormDTO)); 25 26 }
服務類Service

1 public interface DataAcquisitionFileInfoService { 2 3 List<DefinedReportFormVO> defindQuery(DefinedReportFormDTO parameter); 4 5 }
實現類ServiceImpl

1 @SuppressWarnings("unchecked") 2 @Override 3 public List<DefinedReportFormVO> defindQuery(DefinedReportFormDTO parameter) { 4 5 6 /** 7 8 9 * 定義五張表的查詢字符串,年月,和機構id默認查詢 10 */ 11 StringBuilder orgInformationCbrc = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id ,"); 12 StringBuilder orgBasicInformation = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,"); 13 StringBuilder orgBusinessStructure = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,"); 14 StringBuilder orgProfit = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,"); 15 StringBuilder orgBalanceSheets = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,"); 16 17 //定義機構的字符串 18 StringBuilder companyIds = new StringBuilder(""); 19 //查詢所有機構 20 List<Company> orgList = orgService.getOrgList(); 21 22 //拼接所有機構的字符串(如果需要求平均數的話) 23 for (Company company : orgList) { 24 companyIds.append(company.getId()+","); 25 } 26 27 companyIds.deleteCharAt(companyIds.length()-1); 28 //定義每個表的字符串判斷 29 Map<String ,String> bool = new HashMap<>(); 30 31 //指標名 32 List<String> fieldNames = new ArrayList(); 33 //返回結果 34 List<Map<String,Object>> result = new ArrayList<>(); 35 36 //指標名默認添加年月機構id 37 fieldNames.add("reportingYear"); 38 fieldNames.add("reportingMonth"); 39 fieldNames.add("companyId"); 40 //定義指標id集合 41 List ids = parameter.getIds(); 42 //循環所有的指標 43 for (Object id : ids) { 44 //如果指標為空 45 if (!"".equals(id) && id != null) { 46 //根據指標id查詢指標 47 OrgStatisticalIndicators orgStatisticalIndicators = orgStatisticalIndicatorsRespository.findByIdAndAndDelFlag(Long.parseLong(id.toString())); 48 if(("year".equals(parameter.getTimeStyle()) && "0".equals(orgStatisticalIndicators.getYearQuery())) || ("month".equals(parameter.getTimeStyle()) && "0".equals(orgStatisticalIndicators.getMonthQuery()))){ 49 /** 50 * 判斷指標所在的表,然后為各自的表拼接上表的字段 51 */ 52 if ("org_information_cbrc".equals(orgStatisticalIndicators.getTableName())) { 53 orgInformationCbrc.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,"); 54 // 55 if (bool.get("org_information_cbrc") == null) { 56 bool.put("org_information_cbrc", orgStatisticalIndicators.getTableField()); 57 } 58 //如果其他表不存在這個屬性則為其他表拼接null 59 orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ","); 60 orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ","); 61 orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ","); 62 orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); 63 64 //行業平均 65 if (parameter.isAvg()) { 66 if("year".equals(parameter.getTimeStyle())){ 67 orgInformationCbrc.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,"); 68 }else{ 69 orgInformationCbrc.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 70 } 71 72 73 orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 74 75 orgBasicInformation.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 76 77 orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 78 79 orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 80 81 82 83 84 } 85 86 87 } else if ("org_basic_information".equals(orgStatisticalIndicators.getTableName())) { 88 if (bool.get("org_basic_information") == null) { 89 bool.put("org_basic_information", orgStatisticalIndicators.getTableField()); 90 } 91 92 orgBasicInformation.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,"); 93 orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ","); 94 orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ","); 95 orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ","); 96 orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); 97 98 //行業平均 99 if (parameter.isAvg()) { 100 if("year".equals(parameter.getTimeStyle())){ 101 orgBasicInformation.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,"); 102 }else{ 103 orgBasicInformation.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 104 } 105 106 orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 107 orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 108 orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 109 orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 110 111 } 112 113 } else if ("org_business_structure".equals(orgStatisticalIndicators.getTableName())) { 114 orgBusinessStructure.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,"); 115 if (bool.get("org_business_structure") == null) { 116 bool.put("org_business_structure", orgStatisticalIndicators.getTableField()); 117 } 118 119 120 orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ","); 121 orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ","); 122 orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ","); 123 orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); 124 125 //行業平均 126 if (parameter.isAvg()) { 127 if("year".equals(parameter.getTimeStyle())){ 128 orgBusinessStructure.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,"); 129 }else{ 130 orgBusinessStructure.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 131 } 132 133 orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 134 orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 135 orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 136 orgBasicInformation.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 137 138 139 140 141 142 } 143 } else if ("org_profit".equals(orgStatisticalIndicators.getTableName())) { 144 orgProfit.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,"); 145 if (bool.get("org_profit") == null) { 146 bool.put("org_profit", orgStatisticalIndicators.getTableField()); 147 } 148 149 orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ","); 150 orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ","); 151 orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ","); 152 orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ","); 153 154 //行業平均 155 if (parameter.isAvg()) { 156 if("year".equals(parameter.getTimeStyle())){ 157 orgProfit.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,"); 158 }else{ 159 orgProfit.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 160 } 161 162 orgBasicInformation.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 163 orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 164 orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 165 orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 166 167 168 169 } 170 171 } else if ("org_balance_sheets".equals(orgStatisticalIndicators.getTableName())) { 172 orgBalanceSheets.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,"); 173 if (bool.get("org_balance_sheets") == null) { 174 bool.put("org_balance_sheets", orgStatisticalIndicators.getTableField()); 175 } 176 177 178 orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ","); 179 orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ","); 180 orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ","); 181 orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); 182 183 //行業平均 184 if (parameter.isAvg()) { 185 if("year".equals(parameter.getTimeStyle())){ 186 orgBalanceSheets.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,"); 187 }else{ 188 orgBalanceSheets.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 189 } 190 191 192 orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 193 orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 194 orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 195 orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); 196 197 } 198 } 199 if (parameter.isAvg()==true) { 200 fieldNames.add(orgStatisticalIndicators.getField()); 201 fieldNames.add(orgStatisticalIndicators.getField()+"Avg"); 202 } else { 203 fieldNames.add(orgStatisticalIndicators.getField()); 204 } 205 206 } 207 208 } 209 } 210 211 212 //拼接where條件 213 StringBuilder whereSql = new StringBuilder(" WHERE 1 = 1"); 214 215 216 if("year".equals(parameter.getTimeStyle())){ 217 whereSql.append(" AND reporting_year >= :startYear and reporting_year <= :endYear AND reporting_month = '12' "); 218 }else{ 219 whereSql.append(" and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) )>= :startYear and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) ) <= :endYear"); 220 } 221 222 //獲取所有機構id 223 List parameterCompanyIds = parameter.getCompanyIds(); 224 //如果機構id不為空 225 if (parameterCompanyIds.size()>0) { 226 whereSql.append(" AND company_id in ( "); 227 228 229 for (int i = 0; i < parameterCompanyIds.size(); i++) { 230 whereSql.append(":s"+i+" ,"); 231 } 232 233 whereSql.deleteCharAt(whereSql.length()-1); 234 whereSql.append(" )"); 235 } 236 237 //定義Query 238 Query orgBalanceSheetsQuery = null; 239 240 241 242 //拼接五張表和條件 243 orgBalanceSheets.deleteCharAt(orgBalanceSheets.length()-1); 244 orgBalanceSheets.append(" from org_balance_sheets "); 245 orgBalanceSheets.append(whereSql); 246 247 orgBasicInformation.deleteCharAt(orgBasicInformation.length()-1); 248 orgBasicInformation.append(" from org_basic_information "); 249 orgBasicInformation.append(whereSql); 250 251 orgBusinessStructure.deleteCharAt(orgBusinessStructure.length()-1); 252 orgBusinessStructure.append(" from org_business_structure "); 253 orgBusinessStructure.append(whereSql); 254 255 orgInformationCbrc.deleteCharAt(orgInformationCbrc.length()-1); 256 orgInformationCbrc.append(" from org_information_cbrc "); 257 orgInformationCbrc.append(whereSql); 258 259 260 orgProfit.deleteCharAt(orgProfit.length()-1); 261 orgProfit.append(" from org_profit "); 262 orgProfit.append(whereSql); 263 264 265 //關聯五張表 266 orgBalanceSheets.append(" UNION "); 267 orgBalanceSheets.append(orgBasicInformation.toString()); 268 269 orgBalanceSheets.append(" UNION "); 270 orgBalanceSheets.append(orgBusinessStructure.toString()); 271 272 orgBalanceSheets.append(" UNION "); 273 orgBalanceSheets.append(orgInformationCbrc.toString()); 274 275 orgBalanceSheets.append(" UNION "); 276 orgBalanceSheets.append(orgProfit.toString()); 277 278 279 System.out.println(">>"+orgBalanceSheets.toString()); 280 281 282 //創建本地sql查詢實例 283 orgBalanceSheetsQuery = entityManager.createNativeQuery(orgBalanceSheets.toString()); 284 285 //如果時間為空那就獲取現在的時間 286 if(parameter.getEndTime() == null){ 287 parameter.setEndTime(new Date()); 288 } 289 if(parameter.getStartTime() == null){ 290 parameter.setStartTime(new Date()); 291 } 292 293 294 if("year".equals(parameter.getTimeStyle())){ 295 296 orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy")); 297 298 orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy")); 299 }else if("month".equals(parameter.getTimeStyle())){ 300 301 302 orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy-MM")); 303 304 orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy-MM")); 305 306 307 } 308 309 310 311 312 if (parameterCompanyIds.size()>0) { 313 314 for (int i = 0; i < parameterCompanyIds.size(); i++) { 315 orgBalanceSheetsQuery.setParameter("s"+i, parameterCompanyIds.get(i)); 316 } 317 } 318 319 320 //獲取數據 321 List resultList = orgBalanceSheetsQuery.getResultList(); 322 323 324 System.out.println("resultList==="+resultList); 325 326 //給數據設置屬性 327 for (int i = 0; i < resultList.size(); i++) { 328 Object o = resultList.get(i); 329 Object[] cells = (Object[]) o; 330 Map<String,Object> map = new HashMap<>(); 331 if(cells.length == 3){ 332 continue; 333 } 334 for (int j = 0; j<cells.length; j++) { 335 336 if (cells[j] != null && !"".equals(cells[j].toString())) { 337 map.put((String) fieldNames.get(j),cells[j]); 338 }else{ 339 setField(resultList,fieldNames,map,i,j); 340 } 341 342 } 343 result.add(map); 344 } 345 346 System.out.println("result == "+result); 347 348 349 List<DefinedReportFormVO> definedReportFormVOList = new ArrayList<>(); 350 Map<String,List> stringListMap = new HashMap<>(); 351 352 353 354 //定義返回的格式 355 for (Map<String, Object> map : result) { 356 String reportingYear = (String) map.get("reportingYear"); 357 String reportingMonth = (String) map.get("reportingMonth"); 358 String reportingDate = reportingYear+"-"+reportingMonth; 359 //如果時間類型是年 360 if ("year".equals(parameter.getTimeStyle())) { 361 List list = stringListMap.get(reportingYear); 362 if (list != null) { 363 list.add(map); 364 stringListMap.put(reportingYear,list); 365 }else{ 366 List inner =new ArrayList(); 367 inner.add(map); 368 stringListMap.put(reportingYear,inner); 369 } 370 }else{//如果為月 371 372 List list = stringListMap.get(reportingDate); 373 if (list != null) { 374 list.add(map); 375 stringListMap.put(reportingDate,list); 376 }else{ 377 List inner =new ArrayList(); 378 inner.add(map); 379 stringListMap.put(reportingDate,inner); 380 } 381 } 382 383 } 384 385 System.out.println("stringListMap == "+stringListMap); 386 387 388 for (Map.Entry<String,List> entry : stringListMap.entrySet()) { 389 DefinedReportFormVO formVO = new DefinedReportFormVO(); 390 formVO.setTime(entry.getKey()); 391 392 if(parameter.isAvg()==true){ 393 formVO.setArr(setAvg(entry.getValue(),fieldNames)); 394 }else{ 395 formVO.setArr(entry.getValue()); 396 } 397 398 definedReportFormVOList.add(formVO); 399 400 } 401 402 403 return definedReportFormVOList; 404 }
指標實體

1 /** 2 * 統計指標 3 */ 4 @Entity 5 @Table(name = "org_statistical_indicators", catalog = "zhsupervision") 6 public class OrgStatisticalIndicators { 7 @Id 8 @GeneratedValue 9 private Long id; 10 /** 11 * 前端顯示名 12 */ 13 private String name; 14 /** 15 * 表屬性 16 */ 17 private String tableField; 18 /** 19 * 表名稱 20 */ 21 private String tableName; 22 /** 23 * 創建時間 24 */ 25 private Date createTime; 26 /** 27 * 更新時間 28 */ 29 private Date updateTime; 30 /** 31 * 刪除標識 32 */ 33 private String delFlag; 34 //父節點 35 private Long pId; 36 //屬性 37 private String field; 38 //該指標查詢月的時候是否查詢 39 private String monthQuery; 40 //該指標查詢年的時候是否查詢 41 private String yearQuery; 42 43 public String getMonthQuery() { 44 return monthQuery; 45 } 46 47 public void setMonthQuery(String monthQuery) { 48 this.monthQuery = monthQuery; 49 } 50 51 public String getYearQuery() { 52 return yearQuery; 53 } 54 55 public void setYearQuery(String yearQuery) { 56 this.yearQuery = yearQuery; 57 } 58 59 public String getField() { 60 return field; 61 } 62 63 public void setField(String field) { 64 this.field = field; 65 } 66 67 public Long getId() { 68 return id; 69 } 70 71 public void setId(Long id) { 72 this.id = id; 73 } 74 75 public Long getpId() { 76 return pId; 77 } 78 79 public void setpId(Long pId) { 80 this.pId = pId; 81 } 82 83 public String getName() { 84 return name; 85 } 86 87 public void setName(String name) { 88 this.name = name; 89 } 90 91 public String getTableField() { 92 return tableField; 93 } 94 95 public void setTableField(String tableField) { 96 this.tableField = tableField; 97 } 98 99 public String getTableName() { 100 return tableName; 101 } 102 103 public void setTableName(String tableName) { 104 this.tableName = tableName; 105 } 106 107 public Date getCreateTime() { 108 return createTime; 109 } 110 111 public void setCreateTime(Date createTime) { 112 this.createTime = createTime; 113 } 114 115 public Date getUpdateTime() { 116 return updateTime; 117 } 118 119 public void setUpdateTime(Date updateTime) { 120 this.updateTime = updateTime; 121 } 122 123 public String getDelFlag() { 124 return delFlag; 125 } 126 127 public void setDelFlag(String delFlag) { 128 this.delFlag = delFlag; 129 } 130 131 132 }
指標Service

1 /** 2 * 統計指標服務類 3 */ 4 public interface OrgStatisticalIndicatorsService { 5 /** 6 * 根據id獲取 7 * @param id 8 * @return 9 */ 10 OrgStatisticalIndicators findOrgStatisticalIndicatorsById(Long id); 11 12 /** 13 * 根據表名查詢 14 */ 15 List<OrgStatisticalIndicators> findOrgStatisticalIndicatorsByTableName(String name); 16 17 }
指標serviceImpl

1 @Service 2 public class OrgStatisticalIndicatorsServiceImpl extends BaseServiceImpl<OrgStatisticalIndicators, String> implements OrgStatisticalIndicatorsService { 3 4 @Autowired 5 private OrgStatisticalIndicatorsRespository respository; 6 7 @Override 8 public OrgStatisticalIndicators findOrgStatisticalIndicatorsById(Long id) { 9 return respository.findByIdAndAndDelFlag(id); 10 } 11 12 @Override 13 public List<OrgStatisticalIndicators> findOrgStatisticalIndicatorsByTableName(String name) { 14 return respository.findOrgStatisticalIndicatorsByTableName(name); 15 } 16 }
指標repository

1 public interface OrgStatisticalIndicatorsRespository extends JpaSpecificationExecutor { 2 3 @Query(value = "select * from org_statistical_indicators WHERE ID=?1 and del_flag = '0'",nativeQuery = true) 4 OrgStatisticalIndicators findByIdAndAndDelFlag(Long id); 5 6 @Query(value = "select * from org_statistical_indicators WHERE del_flag = '0' and NAME =?1",nativeQuery = true) 7 OrgStatisticalIndicators findOrgStatisticalIndicatorsByName(String name); 8 9 }
這個repository要繼承 extends JpaRepository<T, ID> 才可以,寫漏了。
上面使用了union 進行表之間的關聯查詢,關聯的表有點多,所以代碼有些長,同時因為表多,指標(表的屬性)有500多個,無法確定查詢的返回實體,所以只能自己根據數據的返回給數據綁定屬性。
寫完之后我發現語句太長並且嵌套了子查詢后執行的時間也變長了,有時候還會卡,所以我優化了一下,指標查詢指標,統計查詢統計這樣的執行時間就變短了,而且后來需求有所改變,有區分年查詢和月查詢。以下是我對實現類和指標實體的修改。
指標實體:

1 /** 2 * 統計指標 3 */ 4 @Entity 5 @Table(name = "org_statistical_indicators", catalog = "zhsupervision") 6 public class OrgStatisticalIndicators { 7 @Id 8 @GeneratedValue 9 private Long id; 10 /** 11 * 前端顯示名 12 */ 13 private String name; 14 /** 15 * 表屬性 16 */ 17 private String tableField; 18 /** 19 * 表名稱 20 */ 21 private String tableName; 22 /** 23 * 創建時間 24 */ 25 private Date createTime; 26 /** 27 * 更新時間 28 */ 29 private Date updateTime; 30 /** 31 * 刪除標識 32 */ 33 private String delFlag; 34 35 private Long pId; 36 37 private String field; 38 39 private String monthQuery; 40 41 private String yearQuery; 42 43 private String isQuery; 44 45 private String avgQuery; 46 47 48 49 50 public String getAvgQuery() { 51 return avgQuery; 52 } 53 54 public void setAvgQuery(String avgQuery) { 55 this.avgQuery = avgQuery; 56 } 57 58 public String getIsQuery() { 59 return isQuery; 60 } 61 62 public void setIsQuery(String isQuery) { 63 this.isQuery = isQuery; 64 } 65 66 public String getMonthQuery() { 67 return monthQuery; 68 } 69 70 public void setMonthQuery(String monthQuery) { 71 this.monthQuery = monthQuery; 72 } 73 74 public String getYearQuery() { 75 return yearQuery; 76 } 77 78 public void setYearQuery(String yearQuery) { 79 this.yearQuery = yearQuery; 80 } 81 82 public String getField() { 83 return field; 84 } 85 86 public void setField(String field) { 87 this.field = field; 88 } 89 90 public Long getId() { 91 return id; 92 } 93 94 public void setId(Long id) { 95 this.id = id; 96 } 97 98 public Long getpId() { 99 return pId; 100 } 101 102 public void setpId(Long pId) { 103 this.pId = pId; 104 } 105 106 public String getName() { 107 return name; 108 } 109 110 public void setName(String name) { 111 this.name = name; 112 } 113 114 public String getTableField() { 115 return tableField; 116 } 117 118 public void setTableField(String tableField) { 119 this.tableField = tableField; 120 } 121 122 public String getTableName() { 123 return tableName; 124 } 125 126 public void setTableName(String tableName) { 127 this.tableName = tableName; 128 } 129 130 public Date getCreateTime() { 131 return createTime; 132 } 133 134 public void setCreateTime(Date createTime) { 135 this.createTime = createTime; 136 } 137 138 public Date getUpdateTime() { 139 return updateTime; 140 } 141 142 public void setUpdateTime(Date updateTime) { 143 this.updateTime = updateTime; 144 } 145 146 public String getDelFlag() { 147 return delFlag; 148 } 149 150 public void setDelFlag(String delFlag) { 151 this.delFlag = delFlag; 152 } 153 }
實現類Impl:

1 @SuppressWarnings("unchecked") 2 @Override 3 public List<DefinedReportFormVO> defindQuery(DefinedReportFormDTO parameter) { 4 5 6 /** 7 * 定義五張表的查詢字符串,年月,和機構id默認查詢 8 */ 9 StringBuilder orgInformationCbrc = new StringBuilder("select ID as cbrcId, reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId,"); 10 StringBuilder orgBasicInformation = new StringBuilder("select ID as basicId ,reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId,"); 11 StringBuilder orgBusinessStructure = new StringBuilder("select ID as businessId ,reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId,"); 12 StringBuilder orgProfit = new StringBuilder("select ID as profitId ,reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId ,"); 13 StringBuilder orgBalanceSheets = new StringBuilder("select ID as balanceId, reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId ,"); 14 /** 15 * 平均數sql 16 */ 17 StringBuilder orgInformationCbrcAvg = new StringBuilder("select reporting_year ,reporting_month , "); 18 StringBuilder orgBasicInformationAvg = new StringBuilder("select reporting_year ,reporting_month , "); 19 StringBuilder orgBusinessStructureAvg = new StringBuilder("select reporting_year ,reporting_month , "); 20 StringBuilder orgProfitAvg = new StringBuilder("select reporting_year ,reporting_month , "); 21 StringBuilder orgBalanceSheetsAvg = new StringBuilder("select reporting_year ,reporting_month , "); 22 23 24 //指標名 25 List<String> fieldNames = new ArrayList(); 26 27 //指標名默認添加年月機構id 28 fieldNames.add("id"); 29 fieldNames.add("reportingYear"); 30 fieldNames.add("reportingMonth"); 31 fieldNames.add("companyId"); 32 33 //記錄是哪一個表的平均數 34 List<String> orgInformationCbrcAvgField = new ArrayList<>(); 35 List<String> orgBasicInformationAvgField = new ArrayList<>(); 36 List<String> orgBusinessStructureAvgField = new ArrayList<>(); 37 List<String> orgProfitAvgField = new ArrayList<>(); 38 List<String> orgBalanceSheetsAvgField = new ArrayList<>(); 39 40 41 orgInformationCbrcAvgField.add("reportingYear"); 42 orgInformationCbrcAvgField.add("reportingMonth"); 43 44 orgBasicInformationAvgField.add("reportingYear"); 45 orgBasicInformationAvgField.add("reportingMonth"); 46 47 orgBusinessStructureAvgField.add("reportingYear"); 48 orgBusinessStructureAvgField.add("reportingMonth"); 49 50 orgProfitAvgField.add("reportingYear"); 51 orgProfitAvgField.add("reportingMonth"); 52 53 orgBalanceSheetsAvgField.add("reportingYear"); 54 orgBalanceSheetsAvgField.add("reportingMonth"); 55 56 57 58 59 //返回前端的結果集 60 List<DefinedReportFormVO> definedReportFormVOList = new ArrayList<>(); 61 //指標結果集 62 Map<String,List<Map<String,Object>>> stringListMap = new HashMap<String,List<Map<String,Object>>>(); 63 //指標Query 64 Query orgBalanceSheetsQuery = null; 65 66 //平均數結果集 67 Map<String,List<Map<String,Object>>> avgListMap = new HashMap<String,List<Map<String,Object>>>(); 68 69 //獲取機構id 70 List parameterCompanyIds = parameter.getCompanyIds(); 71 72 List<OrgStatisticalIndicators> orgStatisticalIndicatorsByIds = orgStatisticalIndicatorsRespository.findOrgStatisticalIndicatorsByIds(parameter.getIds()); 73 74 for (OrgStatisticalIndicators orgStatisticalIndicators : orgStatisticalIndicatorsByIds) { 75 String query = ""; 76 String field = orgStatisticalIndicators.getField(); 77 String isQuery = orgStatisticalIndicators.getIsQuery(); 78 String isAvgQuery = orgStatisticalIndicators.getAvgQuery(); 79 String tableName = orgStatisticalIndicators.getTableName(); 80 /** 81 * 1.前端顯示后端不查詢 82 * 0.前端顯示后端也查詢 83 */ 84 if("1".equals(isQuery)){ 85 continue; 86 } 87 88 /** 89 * year.按照年份查詢 90 * month.按照月查詢 91 */ 92 if("year".equals(parameter.getTimeStyle())){ 93 query = orgStatisticalIndicators.getYearQuery(); 94 }else{ 95 query = orgStatisticalIndicators.getMonthQuery(); 96 } 97 //如果結果為空跳過本次循環 98 if(query == null || "".equals(query)){ 99 continue; 100 } 101 102 /** 103 * 判斷指標所在的表,然后為各自的表拼接上表的字段 104 */ 105 if ("org_information_cbrc".equals(tableName)) { 106 107 if(parameterCompanyIds.size()>0){ 108 orgInformationCbrc.append(query+" ,"); 109 110 //如果其他表不存在這個屬性則為其他表拼接null 111 orgBasicInformation.append("null as "+field+","); 112 orgBalanceSheets.append("null as "+field+","); 113 orgBusinessStructure.append("null as "+field+","); 114 orgProfit.append("null as "+field+","); 115 } 116 117 //行業平均 118 if (parameter.isAvg() ==true && !"1".equals(isAvgQuery)) { 119 orgInformationCbrcAvg.append(" avg("+query+"),"); 120 orgInformationCbrcAvgField.add(field); 121 122 } 123 } else if ("org_basic_information".equals(tableName)) { 124 if(parameterCompanyIds.size()>0){ 125 orgBasicInformation.append(query+" ,"); 126 127 orgInformationCbrc.append("null as "+field+","); 128 orgBalanceSheets.append("null as "+field+","); 129 orgBusinessStructure.append("null as "+field+","); 130 orgProfit.append("null as "+field+","); 131 } 132 133 //行業平均 134 if (parameter.isAvg() && !"1".equals(isAvgQuery)) { 135 orgBasicInformationAvg.append("avg("+query+"),"); 136 orgBasicInformationAvgField.add(field); 137 138 } 139 140 } else if ("org_business_structure".equals(tableName)) { 141 if(parameterCompanyIds.size()>0){ 142 orgBusinessStructure.append(query+" ,"); 143 144 orgBasicInformation.append("null as "+field+","); 145 orgInformationCbrc.append("null as "+field+","); 146 orgBalanceSheets.append("null as "+field+","); 147 orgProfit.append("null as "+field+","); 148 } 149 150 //行業平均 151 if (parameter.isAvg() && !"1".equals(isAvgQuery)) { 152 orgBusinessStructureAvg.append("avg("+query+"),"); 153 orgBusinessStructureAvgField.add(field); 154 } 155 } else if ("org_profit".equals(tableName)) { 156 157 if(parameterCompanyIds.size()>0){ 158 orgProfit.append(query+" AS "+field+" ,"); 159 orgBasicInformation.append("null as "+field+","); 160 orgInformationCbrc.append("null as "+field+","); 161 orgBalanceSheets.append("null as "+field+","); 162 orgBusinessStructure.append("null as "+field+","); 163 } 164 165 //行業平均 166 if (parameter.isAvg() && !"1".equals(isAvgQuery)) { 167 orgProfitAvg.append("avg("+query+"),"); 168 orgProfitAvgField.add(field); 169 } 170 } else if ("org_balance_sheets".equals(tableName)) { 171 if(parameterCompanyIds.size()>0){ 172 orgBalanceSheets.append(query+" ,"); 173 174 orgBasicInformation.append("null as "+field+","); 175 orgInformationCbrc.append("null as "+field+","); 176 orgBusinessStructure.append("null as "+field+","); 177 orgProfit.append("null as "+field+","); 178 } 179 180 //行業平均 181 if (parameter.isAvg() == true && !"1".equals(isAvgQuery)) { 182 183 orgBalanceSheetsAvg.append("avg("+query+"),"); 184 orgBalanceSheetsAvgField.add(field); 185 186 } 187 }else if("org_basic_info_list".equals(tableName)){//因為這幾個字段關聯的是其他表所以使用子查詢 188 189 if(orgStatisticalIndicators.getName().startsWith("銀行")){ 190 if(parameterCompanyIds.size()>0){ 191 orgBasicInformation.append("(SELECT "+query+" FROM "+tableName+" where org_basic_id = ID and type ='1' limit 1) ,"); 192 193 orgInformationCbrc.append("null as "+field+","); 194 orgBalanceSheets.append("null as "+field+","); 195 orgBusinessStructure.append("null as "+field+","); 196 orgProfit.append("null as "+field+","); 197 } 198 199 if(parameter.isAvg() == true && !"1".equals(isAvgQuery)){ 200 orgBasicInformationAvg.append("(SELECT avg("+query+") FROM "+tableName+" where org_basic_id = ID and type ='1' limit 1) ,"); 201 } 202 203 }else if(orgStatisticalIndicators.getName().startsWith("資本")){ 204 if(parameterCompanyIds.size()>0){ 205 orgBasicInformation.append("(SELECT "+query+" FROM "+tableName+" where org_basic_id = ID and type ='0'limit 1) ,"); 206 207 orgInformationCbrc.append("null as "+field+"1,"); 208 orgBalanceSheets.append("null as "+field+"1,"); 209 orgBusinessStructure.append("null as "+field+"1,"); 210 orgProfit.append("null as "+field+"1,"); 211 } 212 if(parameter.isAvg() == true && !"1".equals(isAvgQuery)){ 213 orgBasicInformationAvg.append("(SELECT avg("+query+") FROM "+tableName+" where org_basic_id = ID and type ='0' limit 1) ,"); 214 } 215 } 216 217 if (parameter.isAvg()==true && !"1".equals(isAvgQuery)) { 218 orgBasicInformationAvgField.add(field); 219 } 220 221 } 222 if (!"1".equals(isQuery)) { 223 if(parameterCompanyIds.size()>0){ 224 fieldNames.add(field); 225 } 226 } 227 228 } 229 230 //拼接where條件 231 StringBuilder whereSql = new StringBuilder(" WHERE 1 = 1"); 232 233 234 if("year".equals(parameter.getTimeStyle())){ 235 whereSql.append(" AND reporting_year >= :startYear and reporting_year <= :endYear AND reporting_month = '12' "); 236 }else{ 237 whereSql.append(" and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) )>= :startYear and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) ) <= :endYear"); 238 } 239 240 241 //如果機構id不為空 242 if (parameterCompanyIds.size()>0) { 243 whereSql.append(" AND company_id in ( "); 244 245 246 for (int i = 0; i < parameterCompanyIds.size(); i++) { 247 whereSql.append(":s"+i+" ,"); 248 } 249 250 whereSql.deleteCharAt(whereSql.length()-1); 251 whereSql.append(" )"); 252 } 253 254 255 //拼接五張表和條件 256 orgBalanceSheets.deleteCharAt(orgBalanceSheets.length()-1); 257 orgBalanceSheets.append(" from org_balance_sheets "); 258 orgBalanceSheets.append(whereSql); 259 260 orgBasicInformation.deleteCharAt(orgBasicInformation.length()-1); 261 orgBasicInformation.append(" from org_basic_information "); 262 orgBasicInformation.append(whereSql); 263 264 orgBusinessStructure.deleteCharAt(orgBusinessStructure.length()-1); 265 orgBusinessStructure.append(" from org_business_structure "); 266 orgBusinessStructure.append(whereSql); 267 268 orgInformationCbrc.deleteCharAt(orgInformationCbrc.length()-1); 269 orgInformationCbrc.append(" from org_information_cbrc "); 270 orgInformationCbrc.append(whereSql); 271 272 273 orgProfit.deleteCharAt(orgProfit.length()-1); 274 orgProfit.append(" from org_profit "); 275 orgProfit.append(whereSql); 276 277 278 //關聯五張表 279 orgBalanceSheets.append(" UNION "); 280 orgBalanceSheets.append(orgBasicInformation.toString()); 281 282 orgBalanceSheets.append(" UNION "); 283 orgBalanceSheets.append(orgBusinessStructure.toString()); 284 285 orgBalanceSheets.append(" UNION "); 286 orgBalanceSheets.append(orgInformationCbrc.toString()); 287 288 orgBalanceSheets.append(" UNION "); 289 orgBalanceSheets.append(orgProfit.toString()); 290 291 //如果有選機構 292 if(parameterCompanyIds.size() > 0){ 293 //創建本地sql查詢實例 294 orgBalanceSheetsQuery = entityManager.createNativeQuery(orgBalanceSheets.toString()); 295 296 //如果時間為空那就獲取現在的時間 297 if(parameter.getEndTime() == null){ 298 parameter.setEndTime(new Date()); 299 } 300 if(parameter.getStartTime() == null){ 301 parameter.setStartTime(new Date()); 302 } 303 304 if("year".equals(parameter.getTimeStyle())){ 305 306 orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy")); 307 308 orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy")); 309 }else if("month".equals(parameter.getTimeStyle())){ 310 311 312 orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy-MM")); 313 314 orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy-MM")); 315 316 317 } 318 319 320 if (parameterCompanyIds.size()>0) { 321 322 for (int i = 0; i < parameterCompanyIds.size(); i++) { 323 orgBalanceSheetsQuery.setParameter("s"+i, parameterCompanyIds.get(i)); 324 } 325 } 326 327 //返回結果 328 List<Map<String,Object>> result = new ArrayList<>(); 329 330 //獲取數據 331 List resultList = orgBalanceSheetsQuery.getResultList(); 332 333 dataEncapsulation(resultList, fieldNames, result); 334 335 // 336 for (Map<String, Object> map : result) { 337 String reportingYear = (String) map.get("reportingYear"); 338 String reportingMonth = (String) map.get("reportingMonth"); 339 String reportingDate = reportingYear+"-"+reportingMonth; 340 //如果時間類型是年 341 if ("year".equals(parameter.getTimeStyle())) { 342 List list = stringListMap.get(reportingYear); 343 if (list != null) { 344 list.add(map); 345 stringListMap.put(reportingYear,list); 346 }else{ 347 List inner =new ArrayList(); 348 inner.add(map); 349 stringListMap.put(reportingYear,inner); 350 } 351 }else{//如果為月 352 353 List list = stringListMap.get(reportingDate); 354 if (list != null) { 355 list.add(map); 356 stringListMap.put(reportingDate,list); 357 }else{ 358 List inner =new ArrayList(); 359 inner.add(map); 360 stringListMap.put(reportingDate,inner); 361 } 362 } 363 364 } 365 366 } 367 368 369 /** 370 * 平均數 371 */ 372 if (parameter.isAvg() == true) { 373 374 //定義Query 375 Query avgQuerey = null; 376 377 String where = ""; 378 /** 379 * 年月查詢sql 380 * 1.年查詢的是本年的第12月的數據 381 * 2.月查詢是查詢開始到結束的數據 382 */ 383 if("month".equals(parameter.getTimeStyle())){ 384 where = " where CONCAT( reporting_year,'-',RIGHT (100 + CAST(reporting_month AS SIGNED),2)) >= :startTime AND CONCAT( reporting_year,'-',RIGHT (100 + CAST(reporting_month AS SIGNED),2)) <= :endTime GROUP BY reporting_year,reporting_month "; 385 }else{ 386 where = " where reporting_year >= :startTime AND reporting_year<= :endTime AND reporting_month = '12' GROUP BY reporting_year,reporting_month "; 387 } 388 389 String startTime = ""; 390 String endTime = ""; 391 /** 392 * 年查詢和月查詢所給時間賦的值是不一樣的 393 */ 394 if("year".equals(parameter.getTimeStyle())){ 395 startTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy"); 396 endTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy"); 397 }else{ 398 startTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy-MM"); 399 endTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy-MM"); 400 } 401 402 //如果有這個集合添加的屬性超過2個(年月默認添加了) 403 if(orgBalanceSheetsAvgField.size()>2){ 404 orgBalanceSheetsAvg.deleteCharAt(orgBalanceSheetsAvg.length()-1); 405 orgBalanceSheetsAvg.append(" from org_balance_sheets "); 406 orgBalanceSheetsAvg.append(where); 407 avgSetValue(avgQuerey,orgBalanceSheetsAvg,startTime,endTime,orgBalanceSheetsAvgField,parameter.getTimeStyle(),avgListMap); 408 } 409 410 if(orgProfitAvgField.size()>2){ 411 orgProfitAvg.deleteCharAt(orgProfitAvg.length()-1); 412 orgProfitAvg.append(" from org_profit "); 413 orgProfitAvg.append(where); 414 avgSetValue(avgQuerey,orgProfitAvg,startTime,endTime,orgProfitAvgField,parameter.getTimeStyle(),avgListMap); 415 } 416 417 if(orgBasicInformationAvgField.size() > 2){ 418 orgBasicInformationAvg.deleteCharAt(orgBasicInformationAvg.length()-1); 419 orgBasicInformationAvg.append(" from org_basic_information "); 420 orgBasicInformationAvg.append(where); 421 avgSetValue(avgQuerey,orgBasicInformationAvg,startTime,endTime,orgBasicInformationAvgField,parameter.getTimeStyle(),avgListMap); 422 } 423 424 if(orgBusinessStructureAvgField.size() > 2){ 425 orgBusinessStructureAvg.deleteCharAt(orgBusinessStructureAvg.length()-1); 426 orgBusinessStructureAvg.append(" from org_business_structure "); 427 orgBusinessStructureAvg.append(where); 428 avgSetValue(avgQuerey,orgBusinessStructureAvg,startTime,endTime,orgBusinessStructureAvgField,parameter.getTimeStyle(),avgListMap); 429 } 430 431 if(orgInformationCbrcAvgField.size() > 2){ 432 orgInformationCbrcAvg.deleteCharAt(orgInformationCbrcAvg.length()-1); 433 orgInformationCbrcAvg.append(" from org_information_cbrc "); 434 orgInformationCbrcAvg.append(where); 435 avgSetValue(avgQuerey,orgInformationCbrcAvg,startTime,endTime,orgInformationCbrcAvgField,parameter.getTimeStyle(),avgListMap); 436 } 437 438 } 439 /** 440 * 1.如果指標查詢的集合為空將平均數的集合賦值給它 441 * 2.如果都有數據就將他們的相同時間段的添加在一起 442 * 3.如果平均數為空就不用操作直接返回指標查詢 443 */ 444 445 if(stringListMap.size() == 0){ 446 stringListMap.putAll(avgListMap); 447 }else if(stringListMap.size() > 0 && avgListMap.size() > 0){ 448 449 for (Map.Entry<String, List<Map<String, Object>>> entry : stringListMap.entrySet()) { 450 System.out.println(entry.getValue()+"=="+entry.getKey()); 451 List<Map<String, Object>> maps = avgListMap.get(entry.getKey()); 452 if(maps != null){ 453 List<Map<String, Object>> mapList = stringListMap.get(entry.getKey()); 454 for (Map<String, Object> map : maps) { 455 mapList.add(map); 456 } 457 458 } 459 } 460 461 } 462 463 464 //綁定Vo對象 465 for (Map.Entry<String, List<Map<String, Object>>> entry : stringListMap.entrySet()) { 466 DefinedReportFormVO formVO = new DefinedReportFormVO(); 467 formVO.setTime(entry.getKey()); 468 formVO.setArr(entry.getValue()); 469 definedReportFormVOList.add(formVO); 470 } 471 472 return definedReportFormVOList; 473 } 474 475 476 /** 477 * 平均數的sql執行、參數設置和結果格式化 478 * @param avgQuerey Query對象 479 * @param orgBalanceSheetsAvg sql 480 * @param startTime 開始時間 481 * @param endTime 結束時間 482 * @param orgBalanceSheetsField 屬性集合 483 * @param timeStyle 時間類型 484 * @param stringListMap 最終結果集 485 */ 486 public void avgSetValue(Query avgQuerey,StringBuilder orgBalanceSheetsAvg, String startTime,String endTime,List<String> orgBalanceSheetsField,String timeStyle,Map<String,List<Map<String,Object>>> stringListMap) { 487 //創建本地sql查詢實例 488 avgQuerey = entityManager.createNativeQuery(orgBalanceSheetsAvg.toString()); 489 490 avgQuerey.setParameter("startTime", startTime); 491 492 avgQuerey.setParameter("endTime", endTime); 493 494 List queryResultList = avgQuerey.getResultList(); 495 496 avgDataEncapsulation(queryResultList, orgBalanceSheetsField,timeStyle,stringListMap); 497 498 } 499 500 /** 501 * 502 * @param resultList 執行sql得到的結果集 503 * @param field 屬性集合 504 * @param result 最終得到的數據 505 */ 506 public void dataEncapsulation(List resultList,List field , List<Map<String,Object>> result){ 507 //給數據設置屬性 508 for (int i = 0; i < resultList.size(); i++) { 509 Object o = resultList.get(i); 510 Object[] cells = (Object[]) o; 511 Map<String,Object> map = new HashMap<>(); 512 if(cells.length <= 4){ 513 continue; 514 } 515 for (int j = 0; j<cells.length; j++) { 516 if (cells[j] != null && !"".equals(cells[j].toString())) { 517 map.put((String) field.get(j),cells[j]); 518 }else{ 519 setField(resultList,field,map,i,j); 520 } 521 } 522 523 result.add(map); 524 } 525 526 } 527 528 /** 529 * 平均數 530 * @param resultList 執行sql得到的結果集 531 * @param fieldNames 屬性集合 532 * @param timeStyle 時間類型 533 * @param stringListMap 最終得到的結果集 534 */ 535 public void avgDataEncapsulation(List resultList,List fieldNames ,String timeStyle,Map<String,List<Map<String,Object>>> stringListMap){ 536 537 //返回結果 538 List<Map<String,Object>> result = new ArrayList<>(); 539 540 //給數據設置屬性 541 for (int i = 0; i < resultList.size(); i++) { 542 Object o = resultList.get(i); 543 Object[] cells = (Object[]) o; 544 Map<String,Object> map = new HashMap<>(); 545 546 for (int j = 0; j<cells.length; j++) { 547 map.put((String) fieldNames.get(j),cells[j]); 548 } 549 //與前端協議好平均數的機構id賦值上avg 550 map.put("companyId","avg"); 551 result.add(map); 552 } 553 554 for (Map<String, Object> map : result) { 555 //獲取年月的數據 556 String reportingYear = (String) map.get("reportingYear"); 557 String reportingMonth = (String) map.get("reportingMonth"); 558 String reportingDate = reportingYear+"-"+reportingMonth; 559 560 //如果時間類型是年 561 if ("year".equals(timeStyle)) { 562 List<Map<String, Object>> list = stringListMap.get(reportingYear); 563 if (list != null) { 564 /** 565 * 將相同月份的屬性合並在一起 566 */ 567 Map<String, Object> objectMap = list.get(0); 568 objectMap.putAll(map); 569 stringListMap.put(reportingYear,list); 570 }else{ 571 List<Map<String,Object>> inner =new ArrayList(); 572 Map<String,Object> field = new HashMap(); 573 for (Map.Entry<String, Object> entry : map.entrySet()) { 574 field.put(entry.getKey(),entry.getValue()); 575 } 576 inner.add(field); 577 stringListMap.put(reportingYear,inner); 578 } 579 }else{//如果為月 580 //查看集合中是否存在該時間段 581 List<Map<String, Object>> list = stringListMap.get(reportingDate); 582 /** 583 * 如果存在,將原本的添加上現在的,不存在就新增一個list添加進去 584 */ 585 if (list != null) { 586 Map<String, Object> objectMap = list.get(0); 587 objectMap.putAll(map); 588 stringListMap.put(reportingDate ,list); 589 }else{ 590 List<Map<String,Object>> inner =new ArrayList(); 591 Map<String,Object> field = new HashMap(); 592 //循環將所有的屬性添加進集合 593 for (Map.Entry<String, Object> entry : map.entrySet()) { 594 field.put(entry.getKey(),entry.getValue()); 595 } 596 inner.add(field); 597 //設置一個新的時間段並添加上該數據 598 stringListMap.put(reportingDate,inner); 599 } 600 } 601 602 } 603 } 604 605 606 607 608 /** 609 * 設置屬性 610 * @param resultList 結果集合 611 * @param fieldNames 屬性集合 612 * @param map map封裝 613 * @param num 當前第幾個 614 * @param index 下標 615 */ 616 public void setField(List resultList,List fieldNames,Map map,int num,int index){ 617 618 int i = num; 619 i++; 620 if(i>=resultList.size()){ 621 return; 622 } 623 624 Object o = resultList.get(i); 625 Object[] cells = (Object[]) o; 626 //判斷當前這個位置是否存在值, 627 if (cells[index] != null && !"".equals(cells[index].toString())) { 628 if(i==resultList.size()){ 629 map.put((String) fieldNames.get(index),null); 630 } 631 map.put((String) fieldNames.get(index),cells[index].toString()); 632 }else{ 633 setField(resultList,fieldNames,map,i,index); 634 } 635 636 }
我這里是把平均查詢和普通的指標的查詢區分開了,對應的我對這些數據的操作就增多了。
我這里有用到機構,做的時候不用影響也不會很大,
以前發生一個請求要很久,現在比之前快了許多,所以有關的一些統計的查詢和子查詢還是要分開的好一點,不然會執行會很慢。可以分開查詢,或者后端進行統計之類的。