做者:wt_better 连接: http://blog.csdn.net/wt_better/article/details/80992014sql
MyBatis的trim标签通常用于去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操做。微信
如下是trim标签中涉及到的属性:mybatis
下面使用几个例子来讲明trim标签的使用。app
一、使用trim标签去除多余的and关键字
有这样的一个例子:ide
<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 会变成这样:.net
SELECT * FROM BLOG WHERE
这会致使查询失败。若是仅仅第二个条件匹配又会怎样?这条 SQL 最终会是这样:设计
SELECT * FROM BLOG WHERE AND title like ‘someTitle’
你可使用where标签来解决这个问题,where 元素只会在至少有一个子元素的条件返回 SQL 子句的状况下才去插入“WHERE”子句。并且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。3d
<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标签也能够完成相同的功能,写法以下:code
<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>
二、使用trim标签去除多余的逗号
有以下的例子: xml
若是红框里面的条件没有匹配上,sql语句会变成以下:
INSERT INTO role(role_name,) VALUES(roleName,)
插入将会失败。
使用trim标签能够解决此问题,只需作少许的修改,以下所示:
其中最重要的属性是
suffixOverrides=","
表示去除sql语句结尾多余的逗号.
注:若是你有兴趣的话,也能够研究下Mybatis逆向工程生成的Mapper文件,其中也使用了trim标签,但结合了foreach、choose等标签,更多的是牵扯到Criterion的源码研究。不过研究完以后,你将熟练掌握mybatis各类标签的使用,学到Criterion的设计思想,对本身的启发将会很大。
微信搜索:【Java小咖秀】,更多精彩等着你,回复“手册”获取两份开心。