当前位置:网站首页>项目 - 如何根据最近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>
边栏推荐
- Some derivation formulas for machine learning backpropagation
- shell的脚本的基本用法
- 浅析重复线性渐变repeating-linear-gradient如何使用
- 【编程题】【Scratch三级】2022.03 冬天下雪了
- Conditional statements of shell (test, if, case)
- 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
- 2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
- 一文读懂 MongoDB 和 MySQL 的差异
- 高并发与多线程之间的难点对比(容易混淆)
- LeetCode刷题——摆动序列#376#Medium
猜你喜欢

搭建zabbix监控及邮件报警(超详细教学)

Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software

MySql的安装配置超详细教程与简单的建库建表方法

R——避免使用 col=0

批量免费文字翻译

Redux state management

自动翻译软件-批量批量自动翻译软件推荐

Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record

uni-app生命周期

深度解析 z-index
随机推荐
Bulk free text translation
数据库原理作业2 — JMU
gstreamer's caps event and new_segment event
剑指offer(一)
In-depth analysis of z-index
One of the small practical projects - food alliance ordering system
DirectExchange switch simple introduction demo
什么是浮动?什么是文档流?清除浮动的几种方式及原理?什么是BFC,如何触发BFC,BFC的作用
【并发编程】ReentrantLock的lock()方法源码分析
银河麒麟服务器v10 sp1安装.net6
Koa框架的基本使用
编辑时过滤当前节点及根据限制的层数过滤数据
nohup principle
Project exercise - memorandum (add, delete, modify, check)
LeetCode刷题——摆动序列#376#Medium
Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题
单点登录 思维导图
shell之条件语句(test、if、case)
银河麒麟v10 sp1 安装 PostgreSQL 11.16
第三方库-store