一、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>

 

  运行结果:

 

posted on 2021-09-07 17:23  格物致知_Tony  阅读(971)  评论(0编辑  收藏  举报

目录导航