Mybatis的xml中使用if/else标签

使用if标签进行查询

		SELECT
			orderNo,
			adname,
			orderstatus
		FROM
			order_A
		where
			<if test="order!=null">
				order=#{order}
			</if>
			<if test="title!=null">
				and title=#{title}
			</if>

需要注意的是:如果第一个if的order为null的话 第二值title也为null的话运行会报错,就算第一个if等于null 那么查询语句变成 where and title='哈哈哈' 这样运行的话也会出现错误。

where标签出场

		SELECT
			orderNo,
			adname,
			orderstatus
		FROM
			order_A
		<where>
			<if test="order!=null">
				order=#{order}
			</if>
			<if test="order!=null">
				and title=#{title}
			</if>
		</where>

where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入WHERE子句。而且,若语句的开头为AND或OR,where 元素也会将它们去除。这个只能解决2个值都为空。
不能解决order值为空但是title值为空时还是会出现语句错误的情况,这个时候我们可以在and 前面用1=1或者true来解决
如:
在这里插入图片描述
或这样
在这里插入图片描述

if/else 使用 choose,when,otherwise 代替

由于Mybatis中没有else标签但是可以通过choose,when,otherwise来使用

SELECT
			orderNo,
			adname,
			orderstatus
FROM
	<choose>
		<when test=" platformtype != null and platformtype.trim() != '' and platformtype == 1">
			 `orders_A` as orderTable
		</when>
		<when test=" platformtype != null and platformtype.trim() != '' and platformtype == 2">
			 `orders_B` as orderTable
		</when>
		<when test="  platformtype != null and platformtype.trim() != '' and platformtype == 3">
			 `orders_C` as orderTable
		</when>
		<otherwise>
			 `orders_A` as orderTable
		</otherwise>
	</choose>

翻译一下上面的语句:

当platformtype 值不为空并且把platformtype 值进行去除空字符串,并且值等于1时
就会把表orders_A进行拼接,如果条件都不符合的话就会走otherwise标签默认拼接orders_A表进行查询

choose,when,otherwise标签有点像Java中的switch 当where的test值满足时会拼接里面的表,otherwise表示其他when标签都不满足时执行拼接

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hi梅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值