MyBatis + MyBatis Plus日期范围的查询问题

这篇博客探讨了在前后端交互中处理日期类型数据的两种情况:字符串类型和Date类型,并展示了如何构建对应的SQL查询条件。内容涉及到日期格式化、字符串转日期函数以及在MyBatis中使用条件构造SQL的方式。同时,提到了使用MP(MyBatis-Plus)进行动态SQL生成的示例,强调了日期字符串需要符合特定格式。文章最后指出,根据实际场景选择合适的处理方式,字符串处理相对更灵活。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

情况1:从前端接收到字符串类型的日期

 <if test="startTime!=null and startTime.trim() neq ''">
    and date_format(p.create_time,'%Y-%m-%d %H:%i:%s') &gt;= str_to_date(#{startTime},'%Y-%m-%d %H:%i:%s')
  </if>
  <if test="endTime!=null and endTime.trim() neq ''">
    and date_format(p.create_time,'%Y-%m-%d %H:%i:%s') &lt;= str_to_date(#{endTime},'%Y-%m-%d %H:%i:%s')
  </if>

或者

 <if test="beginTime != null and beginTime !='' ">
     and  <![CDATA[p.create_time >=DATE_ADD(#{beginTime },interval 1 day)]]>
 </if>
 <if test="endTime != null and endTime !=''">
     and  <![CDATA[p.create_time <=DATE_ADD(#{endTime},interval 1 day)]]>
 </if>

情况2:从前端接收到Date类型

 <if test="beginTime !=null">
     <![CDATA[and DATE_FORMAT(t1.create_Time,'%Y-%m-%d')<=DATE_FORMAT(#{beginTime },'%Y-%m-%d')]]>
 </if>
 <if test="endTime !=null">
     <![CDATA[and DATE_FORMAT(t1.create_Time,'%Y-%m-%d')>=DATE_FORMAT(#{endTime },'%Y-%m-%d')]]>
 </if>

情况3:从前端接收到字符串类型的日期,结合MP

List<CustomerIntegral> customerIntegrals = customerIntegralService.list(new QueryWrapper<CustomerIntegral>().
        apply(StringUtils.isNotEmpty(todayString ),"date_format (create_time,'%Y-%m-%d') >= date_format('" + todayString + "','%Y-%m-%d')").
        apply(StringUtils.isNotEmpty(tomorrowString ),"date_format (create_time,'%Y-%m-%d') <= date_format('" + tomorrowString + "','%Y-%m-%d')"
        ));

打印出的SQL

SELECT
	customer_integral_id,
	customer_data_id,
	integral,
	update_id,
	change_status,
	create_id,
	create_time,
	update_time,
	consumption_reasons 
FROM
	customer_integral 
WHERE
	date_format ( create_time, '%Y-%m-%d' ) >= date_format( 'yyyy-MM-dd', '%Y-%m-%d' ) 
	AND date_format ( create_time, '%Y-%m-%d' ) <= date_format( 'yyyy-MM-dd', '%Y-%m-%d' )

这个要注意的是todayString和tomorrowString 必须是格式化的字符串类型
如: yyyy-MM-dd hh:mm:ss

具体场景可以选用具体情况,一般是传字符串比较好处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值