29

MyBatis基础知识点:trim标签的使用

 3 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ%3D%3D&%3Bmid=2452972263&%3Bidx=2&%3Bsn=fe96771adcb9f7e7e63ec14800944082
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

点击上方“ 搜云库技术团队 ”关注,选择“ 设为星标

回复“ 面试题 ”领 《96份:3265页面试题》

MyBatis的trim标签一般用于去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操作。

以下是trim标签中涉及到的属性:

7rMZr2i.png!web

下面使用几个例子来说明trim标签的使用。

1、使用trim标签去除多余的and关键字

有这样的一个例子:

<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>

2、使用trim标签去除多余的逗号

有如下的例子:

MrUzUbu.png!web

如果红框里面的条件没有匹配上,sql语句会变成如下:

INSERT INTO role(role_name,) VALUES(roleName,)

插入将会失败。

使用trim标签可以解决此问题,只需做少量的修改,如下所示:

QfqQn2Z.png!web

其中最重要的属性是

suffixOverrides=","

表示去除sql语句结尾多余的逗号.

注:如果你有兴趣的话,也可以研究下Mybatis逆向工程生成的Mapper文件,其中也使用了trim标签,但结合了foreach、choose等标签,更多的是牵扯到Criterion的源码研究。不过研究完之后,你将熟练掌握mybatis各种标签的使用,学到Criterion的设计思想,对自己的启发将会很大。

作者: wt_better

blog.csdn.net/wt_better/article/details/80992014

《第2版:互联网大厂面试题》

最近又赶上跳槽的高峰期,好多粉丝,都问我要有没有最新面试题,索性,我就把我看过的和我面试中的真题,及答案都整理好, 整理了 《第2版:互联网大厂面试题》 分类  92  PDF 累计 3625页! 我会持续更新中,马上就出第三版,涵盖大厂算法会更多!

IFR7viR.png!web

第2版:题库非常全面

包括 Java 集合、JVM、多线程、并发编程、设计模式、Spring全家桶、Java、MyBatis、ZooKeeper、Dubbo、Elasticsearch、Memcached、MongoDB、Redis、MySQL、RabbitMQ、Kafka、Linux、Netty、Tomcat、Python、HTML、CSS、Vue、React、JavaScript、Android 大数据、阿里巴巴等大厂面试题等、等技术栈!

第2版:面试题,怎么领取?

扫码关注, 我另一个公众号 架构师专栏

(对,就是我小号)

没错,扫码关注,即可下载

(这是神奇的二维码,你不用回复关键字)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK