在日常开发中,我们会经常统计。本次统计针对的技术体系是mybatis plus,实现的功能是使用mybatis plus统计一个月,一年,一周,同时在缺少统计的时间段自动补全上。为了避免重复轮子,写下博客记录。
前提条件:添加hutool工具包依赖
传参实体
@Data
public class DeviceProcessModel implements Serializable {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("统计开始时间")
private Date start;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("统计结束时间")
private Date end;
@ApiModelProperty("策略 1:近一周 2:近一个月 3:近一年 4:自定义时间,前端传入")
private Integer strategy ;
public void init(){
if(4!=strategy){
end = new Date();
start = getDateNew(strategy);
}
}
public static Date getDateNew(Integer strategy){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String format = sdf.format(new Date());
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(format));
} catch (ParseException e) {
e.printStackTrace();
}
if(strategy==1){
DateTime dateTime = DateUtil.lastWeek();
calendar.setTime(dateTime.toJdkDate());
}else if (strategy==2) {
calendar.add(Calendar.MONTH, -1);
} else if (strategy==3) {
calendar.add(Calendar.YEAR, -1);
}
Date date = calendar.getTime();
return date;
}
}
mybatis plus部分核心代码实现
QueryWrapper<DeviceAlertProcess> uvWrapper = new QueryWrapper<>();
uvWrapper.ge(model.getStart()!=null,"create_time",model.getStart());
uvWrapper.le(model.getEnd()!=null,"create_time",model.getEnd());
uvWrapper.groupBy("DATE_FORMAT(create_time,'%Y-%m')");
uvWrapper.select("DATE_FORMAT(create_time,'%Y-%m') as day,ifnull(count(distinct visitor_ip),0) as num");
List<Map<String, Object>> mapList = this.baseMapper.selectMaps(uvWrapper);
computeDayList(model.getStart(),model.getEnd(),mapList);
private void computeDayList(Date start, Date end, List<Map<String, Object>> data){
List<String> day = data.parallelStream().map(s -> s.get("day").toString()).collect(Collectors.toList());
List<DateTime> dateTimes = DateUtil.rangeToList(start, end, DateField.MONTH);
Map<String,Object> map = null;
for(DateTime dateTime:dateTimes){
String format = DateUtil.format(dateTime, "yyyy-MM");
if(!day.contains(format)){
map = new HashMap<>(2);
map.put("day",format);
map.put("num",0);
day.add(format);
data.add(map);
}
}
// 排序
data.sort((o1, o2) -> o1.get("day").toString().compareTo(o2.get("day").toString()));
}