使用Dto将数据封装成普通的JavaBeans

时间:2022-09-24 08:16:06

使用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));

 

  这样就省去了多次请求的弊端。