Mybatis中如何查询时间段内的数据

前面是遇到的问题,可以直接跳过看最后解决方法的最后一个demo

问题:

这样的写法会增加许多不必要的逻辑判断

  • demo1

当其中有一个参数为空的时候,这个sql就不会被执行

<if test="beginDate != null and beginDate != '' and endDate != null and endDate != ''">
            stock_bill.bill_date between #{beginDate} and #{endDate}
 </if>
  • demo2

此时我们将and改为or,但当一个参数为空时,会报错

 <if test="beginDate != null and beginDate != '' or endDate != null and endDate != ''">
          AND stock_bill.bill_date between #{beginDate} and #{endDate}
 </if>

解决方案

  • demo3

将条件拆开后,但><号不符合xml规范

<if test="beginDate != null and beginDate != ''"> AND stock_bill.bill_date >= #{beginDate}</if>
<if test="endDate != null and endDate != ''">AND stock_bill.bill_date <= #{endDate}</if>

  • demo4

把>< 号使用了<![CDATA[ ]]>标签括起来,或者使用mysql中的写法,当然数据库需要是mysql

 <if test="beginDate != null and beginDate != ''">AND stock_bill.bill_date <![CDATA[>=]]> #{beginDate}</if>
 <if test="endDate != null and endDate != ''">AND stock_bill.bill_date <![CDATA[<=]]>#{endDate}</if>
 <if test="beginDate != null and beginDate != ''">AND stock_bill.bill_date &gt;= #{beginDate}</if>
 <if test="endDate != null and endDate != ''">AND stock_bill.bill_date &lt;= #{endDate}</if>
发布了123 篇原创文章 · 获赞 54 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_36750352/article/details/103148104
今日推荐