mybatis 多重if 条件判断
要注意的是
当指定某种情况的时候,条件需要添加 toString() 方法
mybatis常用判断语法(标签)
作为java开发,我们常用的判断有if、switch语句,其实在MyBatis中也有对应的标签,用于动态生成sql语句。
if判断
1 2 3 4 5 |
< where > < if test = "null != statusCode and 0 != statusCode" > AND b.STATUS_CODE = #{statusCode, jdbcType=VARCHAR} </ if > </ where > |
一般来说,很多程序猿朋友会在<if>标签前增加WHERE 1=1语句,但其实只需要像上面代码中增加<where>标签包裹所有<if>语句,<if>内语句前面都有and或者or关键字就行:
MyBatis会自动判断所有条件不满足时,不添加where语句; 如果有多判断语句,并且满足一个条件以上时,会把第一条满足的(如果第一条有and或者or关键字时)and或者or关键字删除;
choose判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
< choose > < when test = "5 == queryType" > CASE WHEN statusCode IN (1,6) THEN 1 ELSE 2 END,createTime DESC </ when > < when test = "1 != queryType and 9 != queryType" > createTime DESC </ when > < otherwise > < choose > < when test = "null == orderType or 1 == orderType" > auditTime </ when > < when test = "2 == orderType" > downloadCount </ when > < when test = "3 == orderType" > browseCount </ when > < otherwise > is666Count </ otherwise > </ choose > < if test = "null == orderMode or 1 == orderMode" > DESC </ if > </ otherwise > </ choose > |
上面的代码使用了标签嵌套特性,用于复杂条件判断。
choose判断跟if else语句作用相同,起到根据条件执行不同分支逻辑的作用。
而otherwise跟多个if else中最后一个else的作用相同,在以上条件都不满足时,执行otherwise中的逻辑。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/qq_39137095/article/details/104750721
查看更多关于mybatis中的多重if 条件判断的详细内容...