• 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>

      运行结果:

  • 相关阅读:
    sql server执行存储过程慢的问题
    Windows service
    moss网站模板的一些问题
    ACM题解报告——HD1012
    ACM题解报告——HD1496
    ACM题解报告——HD1253
    ACM题解报告——进制数取于余
    ACM题解报告——HD1058
    ACM题解报告——HD1548
    ACM解题报告HD1015
  • 原文地址:https://www.cnblogs.com/niujifei/p/15239285.html
Copyright © 2020-2023  润新知