mybatis标签之——<trim>

trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能。

trim属性主要有以下四个

  •  prefix:前缀覆盖并增加其内容
  •  suffix:后缀覆盖并增加其内容
  •  prefixOverrides:前缀判断的条件
  •  suffixOverrides:后缀判断的条件

例如在update中

<update id="updateByPrimaryKey" parameterType="Object">
        update student set 
  <trim  suffixOverrides="," > 
    <if test="name != null  ">
        NAME=#{name},
    </if>
    <if test="hobby != null  ">
        HOBBY=#{hobby},
    </if>
  </trim> where id=#{id}
    </update>

 如果name和hobby的值都不为空的话,会执行如下语句

update student set NAME='XX',HOBBY='XX' /*,*/ where id='XX'

会忽略最后一个“,” ;

在select中

<select id="selectByNameOrHobby" resultMap="BaseResultMap">
select * from student 
<trim prefix="WHERE" prefixOverrides="AND | OR">
    <if test="name != null and name.length()>0"> AND name=#{name}
    </if>
    <if test="hobby != null and hobby.length()>0"> AND hobby=#{hobby}
    </if>
</trim>
</select>

 如果name和hobby的值都不为空的话,会执行如下语句

select * from user WHERE /*and*/ name = ‘xx’ and hobby= ‘xx’

会为<trim>片段添加 "WHERE" 前缀,并忽略第一个 “and”  ;

当然,避免出现“WHERE AND”还有其他方法,如下

<!--将where提取出来,并加上“1=1”的查询条件 -->
select * from student 
where 1=1
<trim suffixOverrides=",">
   <if test="name != null and name != ''">
      and NAME = #{name}
   </if>
   <if test="hobby != null and hobby != ''">
      and HOBBY = #{hobby}
   </if> 
</trim>

用在insert中

    <insert id="insert" parameterType="Object">
        insert into student    <trim     prefix="("    suffix=")"    suffixOverrides="," >
    <if test="name != null  ">
        NAME,
    </if>
    <if test="hobby != null  ">
        HOBBY,
    </if>    
    </trim>    <trim     prefix="values("    suffix=")"    suffixOverrides="," >  
    <if test="name != null  ">
        #{name},
    </if>
    <if test="hobby != null  ">
        #{hobby},
    </if>
    </trim>
    </insert>

可以为生成格式正确的insert语句。

原文地址:https://www.cnblogs.com/zjfjava/p/8882614.html