当前位置:网站首页>项目 - 如何根据最近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>
边栏推荐
- Automatic translation software - batch batch automatic translation software recommendation
- shell之条件语句(test、if、case)
- In-depth analysis of z-index
- 二叉树的还原(反序列化)
- Project exercise - memorandum (add, delete, modify, check)
- 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
- js原型详解
- 银河麒麟v10 sp1 安装 PostgreSQL 11.16
- 批量翻译软件免费【2022最新版】
- TypeScript进阶
猜你喜欢
Analysis of pseudo-classes and pseudo-elements
外贸网站优化-外贸网站优化教程-外贸网站优化软件
SSH远程管理
Run the NPM will pop up to ask "how are you going to open this file?"
讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
Redux状态管理
【云原生】-Docker安装部署分布式数据库 OceanBase
DHCP原理与配置
In-depth analysis of z-index
随机推荐
Obtaining server and client information
SSH远程管理
Shell编程规范与变量
那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
QFileInfo常规方法
搭建zabbix监控及邮件报警(超详细教学)
SQLite数据库连接字符串
讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)
第十六章:构建n(5,7)阶素数幻方
拉格朗日插值及其应用
postgresql源码学习(33)—— 事务日志⑨ - 从insert记录看日志写入整体流程
引导过程和服务控制
自动翻译软件-批量批量自动翻译软件推荐
使用powerDesigner反向工程生成Entity
CHI论文阅读(1)EmoGlass: an End-to-End AI-Enabled Wearable Platform for Enhancing Self-Awareness of Emoti
Basic usage of Koa framework
Oracle 日期函数相关
如何在uni-app中选择一个合适的UI组件库
第三方库-store
二叉树的还原(反序列化)