作为java开发,我们常用的判断有if、switch语句,其实在MyBatis中也有对应的标签,用于动态生成sql语句。

1. if判断

<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关键字删除;

2.choose判断

<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中的逻辑。

更多推荐

mybatis常用判断语法(标签)