使用 Mybatis 对 mysql 查询时间范围
需求:1. 传入开始时间(startTime)和结束时间(endTime), 查询 effective_time 在区间 [startTime, endTime] 中的数据。
Controller 中的时间入参用 String 表示:
// 查询接口,默认查询今年内的数据。
@GetMapping(value = "/getData")
public List<Demo> selectDemoData(@RequestParam(value = "startTime", required = false) String startTime,
@RequestParam(value = "endTime", required = false) String endTime) {
// 校验传入的日期格式
// ...
return demoService.selectDemoData(startTime, endTime);
}
mapper 中的sql操作如下,注意要使用mysql的 str_to_date 函数将字符串转成Date再比较。
<!-- 查询接口,默认查询今年内的数据 -->
<select id="selectDemoData" resultType="Demo">
select *
from `demo`
<where>
<!-- 开始时间和结束时间都为空,则查询今年数据 -->
<if test="(startTime == null or startTime == '') and (endTime == null or endTime == '')">
YEAR(`effective_time`) = YEAR( NOW( ) )
</if>
<!-- 开始时间不为空 -->
<if test="startTime != null and startTime != ''">
and date_format(`effective_time`,'%Y-%m-%d') >= str_to_date(#{startTime},'%Y-%m-%d')
</if>
<!-- 结束时间不为空 -->
<if test="endTime != null and endTime != ''">
and date_format(`effective_time`,'%Y-%m-%d') <= str_to_date(#{endTime},'%Y-%m-%d')
</if>
</where>
</select>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南