使用dto的好處:
1.依據現有的類代碼,即可方便的構造出DTO對象,而無需重新進行分析。
2.減少請求次數,大大提高效率。
3.按需組織DTO對象,頁面需要的字段我才組織,不需要的我不組織,可以避免傳輸整個表的字段,一定程度上提高了安全性。
一般的使用dto都是去繼承實體類,在DTO類里放一些業務字段,並提供get、set方法。當我們在業務邏輯層或者交互層用到一些數據庫中不存在的字段時,我們就需要在DTO類里放這些字段,這些字段的意義就相當於一些經處理過的數據庫字段,實質意義就是方便數據交互,提高效率。
這里我使用dto是為了處理一些業務代碼:
1、dto
1 public class CwqfDataDto { 2 3 //總人數 4 private Integer count; 5 6 //欠費總額度 7 private BigDecimal sum; 8 9 //Obj 10 private Object obj; 11 12 13 14 public CwqfDataDto(Integer count, BigDecimal sum, Object obj) { 15 super(); 16 this.count = count; 17 this.sum = sum; 18 this.obj = obj; 19 } 20 21 public Integer getCount() { 22 return count; 23 } 24 25 public void setCount(Integer count) { 26 this.count = count; 27 } 28 29 public BigDecimal getSum() { 30 return sum; 31 } 32 33 public void setSum(BigDecimal sum) { 34 this.sum = sum; 35 } 36 37 public Object getObj() { 38 return obj; 39 } 40 41 public void setObj(Object obj) { 42 this.obj = obj; 43 } 44 45 46 public static CwqfDataDto CountSumOverallarrears(List<Map<String,Object>> obj) { 47 Integer count=0; 48 BigDecimal sum=new BigDecimal(0.00); 49 for (Map<String, Object> map : obj) { 50 Object object = map.get("ZS"); 51 count=count+new Integer(object.toString()); 52 Object object2 = map.get("QFH"); 53 System.out.println("CountSumOverallarrears:object2:"+object2); 54 sum=sum.add(new BigDecimal(object2.toString())); 55 } 56 sum= sum.setScale(2, BigDecimal.ROUND_HALF_UP); 57 return new CwqfDataDto(count,sum,obj); 58 } 59 60 61 public static CwqfDataDto Arrearsofstudents(List<Map<String,Object>> obj) { 62 Integer count=obj.size(); 63 BigDecimal sum=new BigDecimal(0.00); 64 for (Map<String, Object> map : obj) { 65 Object object2 = map.get("QF"); 66 System.out.println("Arrearsofstudents:object2:"+object2); 67 sum=sum.add(new BigDecimal(object2.toString())); 68 } 69 sum= sum.setScale(2, BigDecimal.ROUND_HALF_UP); 70 return new CwqfDataDto(count,sum,obj); 71 } 72 73 74 @Override 75 public String toString() { 76 return "CwqfDataDto [count=" + count + ", sum=" + sum + ", obj=" + obj + ", getCount()=" + getCount() 77 + ", getSum()=" + getSum() + ", getObj()=" + getObj() + ", getClass()=" + getClass() + ", hashCode()=" 78 + hashCode() + ", toString()=" + super.toString() + "]"; 79 }
2、調用層
1 List<Map<String,Object>> overallarrears = cwQfQkService.SchoolDistrictArrears(); 2 if(overallarrears==null) { 3 return AjaxResult.fail("數據請求異常,沒有找到相應的結果集"); 4 } 5 return AjaxResult.success(CwqfDataDto.CountSumOverallarrears(overallarrears)); 6 7 8 9 10 11 12 List<Map<String,Object>> overallarrears = cwQfQkService.Arrearsofstudents(bj, nj); 13 if(overallarrears==null) { 14 return AjaxResult.fail("數據請求異常,沒有找到相應的結果集"); 15 } 16 return AjaxResult.success(CwqfDataDto.Arrearsofstudents(overallarrears));
這樣就省去了多次請求的弊端。