前言
-
简介
日常开发中,为了代替使用代码进行分支判断,常用Mybatis动态标签进行拼接条件,下面主要介绍choose when 和 if 标签的使用。
案例
概念
-
choose when分支判断
MyBatis 提供了 choose 元素,按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的 sql。类似于 Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
-
if 单个判断
if 是与(and)的关系,而 choose 是或(or)的关系。
-
where 拼接条件
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或 OR 开头的,则它会剔除掉。
使用案例
- xml样例
<select id="selectStudentList" parameterType="com.nbsp.Student" resultMap="com.nbsp.StudentEntity"> SELECT * from STUDENT <where> <choose> <when test="Name!=null and student!='' "> AND name LIKE CONCAT(CONCAT('%', #{student}),'%') </when> <when test="hobby!= null and hobby!= '' "> AND hobby = #{hobby} </when> <otherwise> <if test="AGE!= null and AGE!= '' "> AND AGE = #{age} </if> </otherwise> </choose> </where> </select>
参考链接
-
mybatis的常用动态sql标签
https://blog.csdn.net/qq_39623058/article/details/88779242
-
mybatis if标签判断字符串相等
https://www.cnblogs.com/westward/p/6910856.html
-
Mybatis中的各种标签用法
https://blog.csdn.net/weixin_42968598/article/details/97259464