MyBatis Mapper中的if-else判断

本文将介绍在MyBatis的Mapper中,怎样编写if-else的条件判断语句。

在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 知识!

沉浸于现实的忙碌之中,没有时间和精力思念过去,成功也就不会太远了。——雷音
2 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号