• 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 查/删

    1. <select id="findListByMap" resultMap="resultUser">
    2. select * from smbms_user where 1=1
    3. <if test="userCode != NULL">
    4. and userCode like concat('%',#{userCode},'%')
    5. if>
    6. select>
    7. <resultMap id="resultUser" type="User">
    8. <id property="name" column="userName">id>
    9. resultMap>

    2.if+trim

            if+trim 常用于 增 

    1. <select id="findListByMap" resultMap="resultUser">
    2. select * from smbms_user
    3. <trim prefix="where" suffixOverrides="and">
    4. <if test="userCode != NULL">
    5. userCode like concat('%',#{userCode},'%')
    6. if>
    7. trim>
    8. select>

    trim标签用途用于拼接

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

    3.if+set

                   if+set 常用于 update 改

    1. <update id="updateUser">
    2. update smbms_user
    3. <set>
    4. <if test="userCode != null">userCode = "zhangsan",if>
    5. <if test="userPassword != null">userPassword = "123123",if>
    6. set>
    7. where id = #{id}
    8. update>

    4.foreach

            foreach 一般用于 in 函数

    1. <select id = "findById" parameterType = "list" resultType = "user">
    2. select * from user
    3. <where>
    4. <foreach item = "id" collection = "list" open = "id in (" separator = "," close = ")" >
    5. #{id}
    6. foreach>
    7. where>
    8. select>

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

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

    open: 前缀

    close: 后缀

    separator: 中间以什么隔开

    5.choose(when otherwise)

    1. <choose>
    2. <when test = "条件1">...when>
    3. <when test = "条件2">...when>
    4. <when test = "条件3">...when>
    5. ...
    6. <otherwise>...otherwise>
    7. choose>

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

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

  • 相关阅读:
    2022年武汉专精特新小巨人企业奖励补贴以及申报条件汇总
    数据结构与算法课后题-第五章(哈夫曼树和哈夫曼编码)
    什么是自动化测试框架?我们该如何搭建自动化测试框架?
    隐私计算 FATE - 多分类神经网络算法测试
    MySQL 教程(三)函数
    【owt】p2p 通道建立连接及发布流过程
    【背包九讲——混合背包问题】
    ELK8.1从零搭建
    【愚公系列】2022年11月 .NET CORE工具案例-.NET 7中的Quic通信
    RHCSA相关知识点
  • 原文地址:https://blog.csdn.net/qq_44114187/article/details/132807443