在MyBatis的Mapper中是不支持if-else语句,如下:
if( condition ) {
// ...
} else {
// ...
}我们可以通过choose(即Java的switch语句)语句来进行替换。choose语句的语法如下:
<choose> <when test="测试条件"> 你的SQL语句1 </when> <otherwise> 所有when都没有匹配的默认SQL语句 </otherwise> </choose>
其中:
when 表示一个if语句
otherwise 表示if语句的else语句
实例1:下面Mapper将批量插入用户信息,其中当name为空(null或'')时,插入‘-’符号。age为空时,插入0。代码如下:
<!--批量插入用户-->
<insert id="inserUsers" parameterType="java.util.List">
insert into user(name, age)
values
<foreach collection="list" index="index" item="item" separator=",">
<trim prefix="(" suffix=")" suffixOverrides=",">
<choose>
<when test="item.name != null and item.name !=''">
#{item.name, jdbcType=VARCHAR},
</when>
<otherwise>
'-',
</otherwise>
</choose>
<choose>
<when test="item.age != null and item.age !=''">
#{item.age, jdbcType=INTEGER},
</when>
<otherwise>
0,
</otherwise>
</choose>
</trim>
</foreach>
</insert>实例2:查询用户信息,如果指定了name查询条件,则使用name进行模糊查询(%name%);如果没有指定,则使用“Admin%”进行模糊查询。代码如下:
<result id="userMap" class="">
...
</result>
<select id="getUser" resultMap="userMap">
select id, name, age from user where del_flag=0
<choose>
<when test="name != null and name != '' ">
and name like concat(concat('%', #{name}), '%')
</when>
<otherwise>
and name like 'Admin%'
</otherwise>
</choose>
</select>MyBatis的Mapper中的choose用法就这些,谢谢支持!!!
参考资料:
https://www.cnblogs.com/a8457013/p/8033263.html
点击学习 MyBatis 教程,了解更多的 MyBatis 知识!