用法介绍
choose
标签作用是通过条件判断来拼接 SQL 语句,类似于 Java 中的 switch
语句,从上到下,当有匹配的条件时,跳出 choose
语句;如果所有条件都不成立则执行 otherwise
标签中的内容
语法格式为:
<choose>
<when test=条件1>
...
</when>
<when test=条件2>
...
</when>
<when test=条件3>
...
</when>
...
<otherwise>
...
</otherwise>
</choose>
使用细节
当有条件成立时,就不会继续执行了。
今天就碰到一个同事写的代码,功能是:年月日三个维度查询报表数据
后端使用四个字段来接收前端传的参数,分别是:
- 日查询为:startDate,endDate
- 月查询为:ymDate
- 年查询为:yDate
而这个同事在实现这个功能时,采用了 choose 标签来实现,他的 SQL 语句拼接为:
<choose>
<when test="query.startDate != null and query.startDate != '' and query.endDate != null and query.endDate != ''">
and DATE_FORMAT(treat_start_time,'%Y-%m-%d') between #{query.startDate} and #{query.endDate}
</when>
<when test="query.ymDate != null and query.ymDate != ''">
and DATE_FORMAT(treat_start_time,'%Y-%m') = #{query.ymDate}
</when>
<when test="query.yDate != null and query.yDate != ''">
and DATE_FORMAT(treat_start_time,'%Y') = #{query.yDate}
</when>
</choose>
然后就有测试的同学反馈说,为什么只有按 日
查询可以查到数据,按 年
和 月
都查不到数据,下面给出三种查询的传参:
{
"startDate": "2022",
"endDate": "2022",
"ydate": "2022",
"ymDate": "2022-05",
}
{
"startDate": "2022-05",
"endDate": "2022-05",
"ymDate": "2022-05",
}
{
"startDate": "2022-05-30",
"endDate": "2022-05-30",
"ydate": null,
"ymDate": null,
}
按照他的这种传参方式及 choose
判断方式分析,choose
只会执行第一个条件判断。解决办法为调整 when
条件的判断顺序为:
<choose>
<when test="query.yDate != null and query.yDate != ''">
and DATE_FORMAT(treat_start_time,'%Y') = #{query.yDate}
</when>
<when test="query.ymDate != null and query.ymDate != ''">
and DATE_FORMAT(treat_start_time,'%Y-%m') = #{query.ymDate}
</when>
<when test="query.startDate != null and query.startDate != '' and query.endDate != null and query.endDate != ''">
and DATE_FORMAT(treat_start_time,'%Y-%m-%d') between #{query.startDate} and #{query.endDate}
</when>
</choose>
总结
使用 choose
标签的时候,一定要注意最先需要判断的条件要放在前面,当匹配到某个条件时,就不会判断后面的语句了。