mybatis动态sql

目录

1.if

2.if+trim

3.if+set

4.foreach

5.choose(when otherwise)


        Mybatis 动态SQL 可以在xml映射文件内,以标签的形式编写动态SQL,执行原理是根据表达式的值完成逻辑判断并动态拼接SQL的功能。

        mybatis提供了9种动态SQL标签:trim、where、set、foreach、if、choose、when、otherwise 。


1.if

        if + where 常用于 select 查/删

    <select id="findListByMap" resultMap="resultUser">
        select * from smbms_user where 1=1
        <if test="userCode != NULL">
            and userCode like  concat('%',#{userCode},'%')
        </if>
    </select>


   <resultMap id="resultUser" type="User">
        <id property="name" column="userName"></id>
    </resultMap>

2.if+trim

        if+trim 常用于 增 

   <select id="findListByMap" resultMap="resultUser">
        select * from smbms_user

        <trim prefix="where"  suffixOverrides="and">

            <if test="userCode != NULL">
                 userCode like  concat('%',#{userCode},'%')
            </if>

        </trim>

    </select>

trim标签用途用于拼接

  •  prefix 给sql语句拼接的前缀(整体)
  • suffix 给sql语句拼接的后缀
  • prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由 prefixOverrides 属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
  • suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指 定。

3.if+set

               if+set 常用于 update 改

    <update id="updateUser">
      update smbms_user
        <set>
            <if test="userCode != null">userCode = "zhangsan",</if>
            <if test="userPassword != null">userPassword = "123123",</if>
        </set>
        where id = #{id}
    </update>

4.foreach

        foreach 一般用于 in 函数

<select id = "findById" parameterType = "list" resultType = "user">
    select * from user
    <where>
    	<foreach item = "id"  collection = "list" open = "id in (" separator = "," close = ")" >
            #{id}
        </foreach>
    </where>
</select>

item : 循环后获取的每个对象值

collection : 指定循环集合类型 list,array ,map-key

open: 前缀

close: 后缀

separator: 中间以什么隔开

5.choose(when otherwise)

<choose>
    <when test = "条件1">...</when>
    <when test = "条件2">...</when>
    <when test = "条件3">...</when>
    ...
    <otherwise>...</otherwise>
</choose>

        MyBatis 中动态语句 choose-when-otherwise 类似于 Java 中的 switch-case-default 语句。

        由于 MyBatis 并没有为 if 提供对应的 else 标签,如果想要达到…… 的效果,可以借助 、、 来实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

愚人钊呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值