zoukankan      html  css  js  c++  java
  • MyBatis(五)动态SQL 之 set 标签

    一、set 标签

      set 主要是用于解决修改操作中 SQL 语句中可能多出逗号的问题。

      在接口中声明方法:

    //修改员工信息
    public void updateEmpByCondition(Employee employee);
    

      

       在对应的 xml 中的配置:

      1、使用${} 方式取值

        <!--
            public void updateEmpByCondition(Employee employee);
        -->
    
        <update id="updateEmpByCondition">
            update tbl_employee
            <set>
                <if test="lastName!=null and lastName != ''">
                    last_name = '${lastName}',
                </if>
                <if test="email!=null">
                    email = '${email}',
                </if>
                <if test="gender!=null">
                    gender = '${gender}'
                </if>
            </set>
            where id = ${id}
        </update>

      执行的 SQL 语句:

    update tbl_employee SET last_name = 'Tom', email = 'Tom@126.com', gender = '男' where id = 1
    

      

      如果去掉 gender 的条件呢

    update tbl_employee SET last_name = 'Tom', email = 'Tom@126.com' where id = 1
    

      

      也可以有效的去掉多余的逗号。

      2、使用 #{} 取值

        <!--
            public void updateEmpByCondition(Employee employee);
        -->
        <update id="updateEmpByCondition">
            update tbl_employee
            <set>
                <if test="lastName!=null">
                    last_name = #{lastName},
                </if>
                <if test="email!=null">
                    email = #{email},
                </if>
                <if test="gender!=null">
                    gender = #{gender}
                </if>
            </set>
            where id = #{id}
        </update>

        运行结果:

      3、使用 trim 标签来实现

        其实 set 的功能也可以用 trim 标签来实现。

        即把 set 这个设置为前缀,把 逗号设置成去掉的后缀即可。

        trim 实现:

        <!-- 方式三:使用trim标签 -->
        <update id="updateEmpByCondition">
            update tbl_employee
            <trim prefix="set" suffixOverrides=",">
                <if test="lastName!=null">
                    last_name = #{lastName},
                </if>
                <if test="email!=null">
                    email = #{email},
                </if>
                <if test="gender!=null">
                    gender = #{gender}
                </if>
            </trim>
            where id = #{id}
        </update>

      运行结果:

  • 相关阅读:
    zabbix自定义监控mysql
    [学习笔记]动态树Link-Cut-Tree
    关于 /etc/zabbix/zabbix_agentd.conf 文件 Hostname 文件的说明
    NOIP2018 游记
    Centos7安装Zabbix3.4
    [学习笔记]动态dp
    Java实现 泊松分酒
    关于使用索引的一些经验
    OI生涯回忆录 2017.9.10~2018.11.11
    覆盖索引小结
  • 原文地址:https://www.cnblogs.com/niujifei/p/15239285.html
Copyright © 2011-2022 走看看