mybatis中trim标签使用

trim标签中涉及到的属性

属性 描述
prefix 给SQL语句拼接的前缀
suffix 给SQL语句拼接的后缀
prefixOverrides 去除sql语句前面的关键字或字符,该关键字由prefixOverrides属性,指定,比如改属性指定为“AND“,那么当sql语句的开头为“AND”时候,trim标签将会去除该“AND”
suffixOverrides 去除sql语句后面的关键字或字符,该关键字由suffixOverrides 属性
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG 
  WHERE 
  <if test="state != null">
    state = #{state}
  </if> 
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>

使用where标签
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句,。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG 
  <where> 
    <if test="state != null">
         state = #{state}
    </if> 
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>

使用trim标签

<trim prefix="WHERE" prefixOverrides="AND">
 <if test="state != null">
   state = #{state}
 </if> 
 <if test="title != null">
   AND title like #{title}
 </if>
 <if test="author != null and author.name != null">
   AND author_name like #{author.name}
 </if>
</trim>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38323645/article/details/107285959