Mybatis的trim标签

134 阅读2分钟

Mybatis xml 中的trim标签

本文总结在使用mybatis框架中,常用到的trim标签。

trim

Mybatis具有实现动态SQL的能力,可以通过使用trim标签来拼凑SQL语句。

trim 在英语中有“点缀物”,修剪的意思。可以把‘’标签为一个装饰sql的标签。

标签说明

其基本格式如下:

<trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>
  • prefix:
    • 表示在trim包裹的SQL语句前面添加的指定内容。
  • suffix:
    • 表示在trim包裹的SQL末尾添加指定内容
  • prefixOverrides:
    • 表示去掉(覆盖)trim包裹的SQL的指定首部内容
  • suffixOverrides:
    • 表示去掉(覆盖)trim包裹的SQL的指定尾部内容

mapper接口如下:

public User getUser(@Param("LastName") String lastName,@Param("age") Integer age,@Param("phone") String phone);

常规的xml文件使用如下:

<select id="getUser" result="user">
 select * from user_tab where last_name=#{lastName} and age=#{age} and phone=#{phone}
</select>

prefix 使用示例

<select id="getUser" resultType="user">
 select * from user_tab 
 <trim prefix="where">
  last_name=#{lastName} and age=#{age} and phone=#{phone}
 </trim>
</select>

在动态生成sql的过程中,会将prefix前缀 拼接到 trim标签的外侧,最终得到的sql如下:

select * from user_tab where last_name=#{lastName} and age=#{age} and phone=#{phone}

prefixOverrides 使用

有动态查询语句如下:

<select id="getUser" resultType="user">
 select * from user_tab 
 <trim prefix="where">
  <if test="lastName != null">
   last_name=#{lastName}
  </if>
  <if test="age != null">
   and age=#{age}
  </if>
  <if test="phone != null">
   and phone=#{phone}
  </if>
 </trim>
</select>

在动态sql的查询过程中,如果 lastName为null,所以第一个if不成立,里面的SQL语句不拼接,第二个if里面的and边紧跟在where后面了,语法错误。最终动态生成的sql如下:

 select * from user_tab where and age = ? and phone = ?

为了解决这个问题,只要加上prefixOverride即可,表示把动态生成的sql中,trim标签内的首个“and”去掉。

<select id="getUser" resultType="user">
 select * from user_tab 
 <trim prefix="where" prefixOverrides="and">
  <if test="lastName != null">
   last_name=#{lastName}
  </if>
  <if test="age != null">
   and age=#{age}
  </if>
  <if test="phone != null">
   and phone=#{phone}
  </if>
 </trim>
</select>

suffix使用示例

<select id="getUser" resultType="user">
 select * from user_tab 
 <trim suffix="where id=#{id}">
  update user_tab
   set
    last_name=#{lastName},
    age=#{age},
    phone=#{phone}
 </trim>
</select>

在动态生成sql的过程中,mybatis 会将suffix 前缀 拼接到 trim标签所包含的sql的外侧,最终得到的sql如下:

select * from user_tab where id = ?

suffixOverrides的使用示例

如下的sql:

<update id="updateUser">
  update user_tab
  set
  <if test="lastName != null">
   last_name=#{lastName},
  </if>
  <if test="age != null">
   age=#{age},
  </if>
  <if test="phone != null">
   phone=#{phone}
  </if> 
  where id = #{id}
</update>

在上述的动态sql中,若phone的值为null,则会导致生成的sql语句最后一个符号为“,”,导致生成的sql出错。

update user_tab
  set ast_name=?,  age=?,

为了避免此种情况,可使用trim标签中的suffixOverrides 将最后面的一个符号覆盖掉。即:

<update id="updateUser">
 <trim suffix="where id=#{id}" suffixOverrides=",">
  update user_tab
  set
  <if test="lastName != null">
   last_name=#{lastName},
  </if>
  <if test="age != null">
   age=#{age},
  </if>
  <if test="phone != null">
   phone=#{phone}
  </if> 
 </trim>
</update>

使用场景

trim标签常用于动态生成sql的场景下。