当前位置:网站首页>项目 - 如何根据最近30天、最近14天、最近7天、最近24小时、自定义时间范围查询MySQL中的数据?
项目 - 如何根据最近30天、最近14天、最近7天、最近24小时、自定义时间范围查询MySQL中的数据?
2022-07-31 05:48:00 【追风筝~】
这个需求在工作中常常遇到,之前是针对es中的数据进行查询,现在是针对mysql中的数据进行查询,原理一样。
1. 定义时间范围枚举类
/** * 时间范围枚举:根据最近30天、最近14天、最近7天、最近24小时、自定义时间范围查询 */
@AllArgsConstructor
public enum TimeScopeEnum {
/** * 最近30天 */
LAST_30_DAYS("last_30_days", 30),
/** * 最近14天 */
LAST_14_DAYS("last_14_days",14),
/** * 最近7天 */
LAST_7_DAYS("last_7_days",7),
/** * 最近24小时 */
LAST_24_HOURS("last_24_hours",1);
/** * 前端传入的参数 */
@Getter
private String name;
/** * 对应的天数 */
@Getter
private Integer value;
/** * 根据前端传入参数名称获取TimeScopeEnum * @param name 前端传入参数名称 */
public static TimeScopeEnum getTimeScopeEnumByName(String name){
for (TimeScopeEnum timeScopeEnum : TimeScopeEnum.values()) {
if(timeScopeEnum.name.equals(name)){
return timeScopeEnum;
}
}
return null;
}
}
2. 根据时间区间查询前端请求参数封装
查询最近7天的数据,前端请求路径:
endTime=1651288728694&startTime=1650683928694&timeScope=last_7_days
根据自定义时间区间查询,前端请求路径:
endTime=1652803199999&startTime=1649865600000&timeScope=custom
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AssetsStatisticQo {
@ApiModelProperty("开始时间")
@NotNull(message = "开始时间不能为空")
private Long startTimeStamp;
@ApiModelProperty("结束时间")
@NotNull(message = "结束时间不能为空")
private Long endTimeStamp;
@NotBlank
@ApiModelProperty("时间范围")
private String timeScope;
}
3. 标识自定义时间范围的常量
public class Constant {
/** * 根据自定义时间段查询 */
public static final String CUSTOM_QUERY_TIME = "custom";
}
4. 请求参数开始时间和结束时间处理
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TimeArgumentQo {
/** * 当前时间 */
private final Date now = new Date();
/** * 开始时间 */
private Date startDate;
/** * 结束时间 */
private Date endDate;
/** * 时间范围枚举 */
private TimeScopeEnum timeScopeEnum;
/** * 对前端请求中的时间参数进行处理 * @param startTimeStamp 开始时间戳 * @param endTimeStamp 结束时间戳 * @param timeScopeEnumStr 时间范围枚举 */
public TimeArgumentQo(Long startTimeStamp, Long endTimeStamp, String timeScopeEnumStr){
if(StringUtils.isEmpty(timeScopeEnumStr)){
log.error("input time parameter error. timeScopeStr: {}", timeScopeEnumStr);
throw new BusinessException("input.params.time.error");
}
// 如果是自定义查询时间
if (Constant.CUSTOM_QUERY_TIME.equals(timeScopeEnumStr)) {
if (startTimeStamp != null && startTimeStamp > 0L) {
startDate = DateUtil.date(startTimeStamp);
}
if (endTimeStamp != null && endTimeStamp > 0L) {
endDate = DateUtil.date(endTimeStamp);
}
boolean flag = startDate != null && endDate != null && (startDate.equals(endDate) || startDate.after(endDate));
if (flag) {
log.error("input time parameter error. startDate: {}, endDate: {}", startDate, endDate);
throw new BusinessException("input.params.time.error");
}
} else {
// 如果不是自定义查询时间
timeScopeEnum = TimeScopeEnum.getTimeScopeEnumByName(timeScopeEnumStr);
if (Objects.isNull(timeScopeEnum)) {
log.error("input time parameter error. timeScope: {}.", timeScopeEnumStr);
throw new BusinessException("input.params.time.error");
}
if (TimeScopeEnum.LAST_24_HOURS.equals(timeScopeEnum) || TimeScopeEnum.LAST_7_DAYS.equals(timeScopeEnum)
|| TimeScopeEnum.LAST_14_DAYS.equals(timeScopeEnum)
|| TimeScopeEnum.LAST_30_DAYS.equals(timeScopeEnum)) {
/* 最近24小时,最近x天(x>1) */
startDate = DateUtil.offsetDay(now, -timeScopeEnum.getValue());
endDate = now;
} else {
/* 最近3个月,最近半年 */
startDate = DateUtil.offsetMonth(now, -timeScopeEnum.getValue());
endDate = now;
}
}
}
}
5. 调用方式
① Controller层
@Slf4j
@ResponseResult
@RequestMapping("/api/v1/assetsStatistics")
public class AssetsStatisticController {
@Autowired
private IAssetsStatisticService assetsStatisticService;
/** * 根据条件查询资产数据 */
@PreAuthorize("hasAnyAuthority('superAdmin','safeOperationQuery')")
@GetMapping("/list")
public List<AssetsStatisticVo> queryList(@Validated @ModelAttribute AssetsStatisticQo assetsStatisticQo) {
return assetsStatisticService.queryList(assetsStatisticQo);
}
}
② Service层
@Slf4j
@Service("assetsStatisticService")
public class AssetsStatisticServiceImpl implements IAssetsStatisticService {
@Autowired
private IAssetsStatisticDao assetsStatisticDao;
/** * 查询资产统计列表 * * @param assetsStatisticQo 查询参数 * @return List<AssetsStatisticVo> */
@Override
public List<AssetsStatisticVo> queryList(AssetsStatisticQo assetsStatisticQo) {
// 转换时间区间
TimeArgumentQo timeArgumentQo = new TimeArgumentQo(
assetsStatisticQo.getStartTime(),
assetsStatisticQo.getEndTime(),
assetsStatisticQo.getTimeScope()
);
Date startDate = timeArgumentQo.getStartDate();
Date endDate = timeArgumentQo.getEndDate();
List<AssetsStatisticVo> assetsStatisticVoList = assetsStatisticDao.statisticBranchAssets( startDate, endDate);
return assetsStatisticVoList;
}
}
③ dao层:
@Repository
public interface IAssetsStatisticDao {
/** * 通过条件查询资产数据 * @param startDate 开始时间 * @param endDate 结束时间 * @return List<AssetsStatisticEntity> */
List<AssetsStatisticEntity> queryBranchAssets( @Param("startDate") Date startDate, @Param("endDate") Date endDate);
}
<!-- 通过条件查询资产数据-->
<select id="queryBranchAssets" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/> from t_assets_statistic
<where>
<if test="startDate != null">
and storageTime >= #{startDate}
</if>
<if test="endDate != null">
and storageTime <= #{endDate}
</if>
</where>
</select>
边栏推荐
- LVM和磁盘配额
- 那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
- 浅析伪类和伪元素
- Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
- LeetCode brush # 376 # Medium - swing sequence
- 服务器硬件及RAID配置实战
- 什么是浮动?什么是文档流?清除浮动的几种方式及原理?什么是BFC,如何触发BFC,BFC的作用
- gstreamer的caps event和new_segment event
- 2022.7.29 数组
- 磁盘和储存管理
猜你喜欢
【云原生】-Docker安装部署分布式数据库 OceanBase
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
shell之条件语句(test、if、case)
postgresql源码学习(33)—— 事务日志⑨ - 从insert记录看日志写入整体流程
DirectExchange switch simple introduction demo
浅析瀑布流布局原理及实现方式
Install and use uView
【云原生】-Docker容器迁移Oracle到MySQL
R——避免使用 col=0
2.(1)栈的链式存储、链栈的操作(图解、注释、代码)
随机推荐
防抖和节流
外贸网站优化-外贸网站优化教程-外贸网站优化软件
MySQL笔记下
Detailed explanation of js prototype
What is float?What is document flow?Several ways and principles of clearing floats?What is BFC, how to trigger BFC, the role of BFC
银河麒麟v10 sp1 安装 PostgreSQL 11.16
Hook API
银河麒麟V10 sp1服务器安装英伟达显卡驱动
Third-party library-store
TypeScript进阶
第三方库-store
测试 思维导图
mysql索引失效的常见9种原因详解
Chapter 17: go back to find the entrance to the specified traverse, "ma bu" or horse stance just look greedy, no back to search traversal, "ma bu" or horse stance just look recursive search NXM board
编辑时过滤当前节点及根据限制的层数过滤数据
ls的用法
LVM和磁盘配额
银河麒麟高级服务器v10 sp1 手动加载Raid卡驱动
In-depth analysis of z-index
第十六章:构建n(5,7)阶素数幻方