Mybatis的if else妙用(Choose标签使用)

Mybatis的if else妙用(Choose标签使用)

提示:Mybatis的if else妙用(Choose标签使用)



前言

大概内容:

在Mybatis.xml中有些情况下会遇到像Java项目中的If、else if、else这类的业务场景,但mybatis不支持这样的写法,但有它自己专属的 Choose 标签完美实现了这个功能,下面就是使用详情


提示:以下是本篇文章正文内容,下面案例可供参考

详细介绍

此处的 param是指Mapper层的入参

select 
* 
from
test_table
where 1=1
<choose>  
	<when test="null != param and '1'== param"> 
		and id = #{param}
	</when> 
	<when test="null != param and '2'== param"> 
		and name = #{param}
	</when> 
	<otherwise> 
		and id = "1" order by id
	</otherwise> 
</choose>


1.其中 when 标签相当于if  test里面放的是进入判定的条件
2.他没有else if这回事,统一用when标签就行
3.otherwise标签标识else,如果都不符合的话,默认使用这个标签下的内容 


总结:仰天大笑出门去,我辈岂是蓬蒿人

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis的if-else标签可以用于动态生成SQL语句,根据不同条件生成不同的SQL语句,从而实现灵活的数据查询。以下是if-else标签使用方法: 1. 在SQL语句中使用if-else标签,语法如下: ``` <select id="selectUser" resultType="User"> SELECT * FROM user <where> <if test="id != null"> AND id = #{id} </if> <if test="username != null"> AND username = #{username} </if> </where> </select> ``` 2. 在if标签使用test属性指定条件表达式,如果条件表达式为true,则生成if标签中的SQL语句;否则不生成if标签中的SQL语句。 3. 可以使用多个if标签组合使用,实现多条件查询。 4. 可以使用else标签,实现条件分支,如下所示: ``` <select id="selectUser" resultType="User"> SELECT * FROM user <where> <if test="id != null"> AND id = #{id} </if> <if test="username != null"> AND username = #{username} </if> <if test="age != null and age > 0"> AND age = #{age} </if> <otherwise> AND status = 1 </otherwise> </where> </select> ``` 5. 可以使用choose-when-otherwise标签组合使用,实现多条件分支,如下所示: ``` <select id="selectUser" resultType="User"> SELECT * FROM user <where> <choose> <when test="id != null"> AND id = #{id} </when> <when test="username != null"> AND username = #{username} </when> <when test="age != null and age > 0"> AND age = #{age} </when> <otherwise> AND status = 1 </otherwise> </choose> </where> </select> ``` 6. 可以在if-else标签中嵌套使用if-else标签,实现更加灵活的动态SQL生成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT行业小趴菜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值