使用 Mybatis 对 mysql 查询时间范围

发布时间 2023-04-14 19:31:12作者: 拾月凄辰

Controller 中的时间入参用 String 表示:

// 查询接口,按关键系统和生效日期排序,默认查询一年内的数据。
    @GetMapping(value = "/getData")
    public List<SystemAvailability> selectSystemAvailabilityData(@RequestParam(value = "startTime", required = false) String startTime, 
	@RequestParam(value = "endTime", required = false) String endTime) {
        // 校验传入的日期格式
        // ...
		
        return demoService.selectSystemAvailabilityData(startTime, endTime);
    }

mapper 中的sql操作:

<select id="selectSystemAvailabilityData" resultType="SystemAvailability">
   select * 
   from `demo`
   <where>
       <if test="startTime!=null and startTime.trim() neq ''">
         date_format(`effective_time`,'%Y-%m-%d') &gt;= str_to_date(#{startTime},'%Y-%m-%d')
       </if>
       <if test="endTime!=null and endTime.trim() neq ''">
         and date_format(`effective_time`,'%Y-%m-%d') &lt;= str_to_date(#{endTime},'%Y-%m-%d')
       </if>

       <if test="startTime == null and endTime == null ">
         and YEAR(`effective_time`) = YEAR( NOW( ) )
       </if>
   </where>
</select>