使用 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') &gt;= str_to_date(#{startTime},'%Y-%m-%d')
            </if>

            <!--  结束时间不为空   -->
            <if test="endTime != null and endTime != ''">
                and date_format(`effective_time`,'%Y-%m-%d') &lt;= str_to_date(#{endTime},'%Y-%m-%d')
            </if>
   </where>
</select>
posted @   拾月凄辰  阅读(2269)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示
主题色彩