mybatis的trim标签一般用于去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操作。
<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>
如果这些条件没有一个能匹配上会发生什么?最终这条 SQL 会变成这样:
SELECT * FROM BLOG
WHERE
这会导致查询失败。如果仅仅第二个条件匹配又会怎样?这条 SQL 最终会是这样:
SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’
可以使用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>
<insert id="insertRoleSelective" parameterType="mtdp.po.Role" useGeneratedKeys="true" keyProperty="id">
INSERT INTO role
(
<if test="roleName != null">
role_name,
</if>
<if test="note != nulL">
note
</if>
)
VALUES(
<if test="roleName != null">
</if>
<if test="note != null">
</if>
)
</insert>
如果第二个if里面的条件没有匹配上,sql语句会变成如下:
INSERT INTO role(role_name,) VALUES(roleName,)
插入将会失败。
使用set标签则和上面的where标签一样包裹if标签即可去掉sql语句最后的逗号;
使用trim标签可以解决此问题,只需做少量的修改,如下所示:
其中最重要的属性是:
suffixOverrides=","