MyBatis 3实现时间段精确的查询(转)

效果如下:

说明:

时间范围的查询会存在以下问题:

1、如果单纯采用年月日的形式会出现缺少最后一点的数据,比如要查询2015-09-16到2015-09-17,那么2015-09-17 01:00:00的数据不会被查询出来。无论是使用between and还是<=/>=的形式去实现都会有这样的问题。

解决方法可以这样做:

1、如果是以年月日的形式,那么可以采用动态拼接字符串的形式,最后得到2015-09-16 00:00:00到2015-09-17 23:59:59,如果要更精确可以往毫秒级别加。

2、采用加1天的形式,比如使用DATE_ADD去增加最后一天,最终得到2015-09-16到2015-09-18。

3、在前端时间控件上采用更精确的输入,比如可以选择年月日时分秒的级别,但是如果要精确到毫秒级别的,需要另做处理,还是使用拼接字符串的形式,或者采用增加函数去增加毫秒级别。

4、如果采用DATE_ADD去增加1天,那么会面临一个问题,就是如果2017-09-18 00:00:00的数据就会被查出来,所以解决方法还是字符串拼接的形式会靠谱一些;或者如果用函数增加时间时,最好不要加满到1天。(初步想法,没实践)

5、如果想要优雅的解决,最完美的方式应该是时间戳的形式,比如将时间转成时间戳的形式去查询。

MyBatis的时间段查询方案:

说明:以下只是查询的语句,没涉及到精确到毫秒级别的查询。

<!-- 查询条件:创建开始时间 -->
<if test="createdBegintime!=null and createdBegintime!=''">
    AND CREATED &gt;= #{createdBegintime}
</if>

<!-- 查询条件:创建结束时间 -->
<if test="createdEndtime!=null and createdEndtime!=''">
    AND CREATED &lt;= #{createdEndtime}
</if>
<if test="date!=null">
<![CDATA[
AND CREATE_TIME >= CONCAT(#{date},' 00:00:00')
AND CREATE_TIME <= CONCAT(#{finish},' 23:59:59')
]]>
</if>
<![CDATA[    这里面是sql语句. 大于号.小于号  ]]>   用这个把大于号.小于号包含起来
<select id="selectOrderListByPage" parameterType="com.xhh.webui.system.entity.Order"
resultType="com.xhh.webui.system.entity.Order">
select * from `order`
<where>
<if test="begindate != null and begindate !=''">
createTime&gt;#{begindate,jdbcType=TIMESTAMP}
</if>
<if test="enddate != null and enddate !=''">
and createTime&lt;#{enddate,jdbcType=TIMESTAMP}
</if>
</where>
<if test="sort != null and order != null">
     <![CDATA[ order by ${sort} ${order} ]]>
</if>
LIMIT #{start},#{rows}
</select

参考:

http://www.cnblogs.com/zhangliang88/p/5479682.html

http://www.jquerycn.cn/a_15385

http://blog.csdn.net/luckyboyguo/article/details/50427086

http://blog.csdn.net/zl544434558/article/details/24428307?utm_source=tuicool&utm_medium=referral

http://www.cnblogs.com/winner-0715/p/5912157.html

http://bbs.csdn.net/topics/391838987

原文地址:https://www.cnblogs.com/EasonJim/p/7513743.html