mybatis trim標籤的使用

2022-06-14 05:36:11 字數 2584 閱讀 7213

mybatis的trim標籤一般用於去除sql語句中多餘的and關鍵字,逗號,或者給sql語句前拼接 「where「、「set「以及「values(「 等字首,或者新增「)「等字尾,可用於選擇性插入、更新、刪除或者條件查詢等操作。

以下是trim標籤中涉及到的屬性:

屬性描述

prefix

給sql語句拼接的字首

suffix

給sql語句拼接的字尾

prefixoverrides

去除sql語句前面的關鍵字或者字元,該關鍵字或者字元由prefixoverrides屬性指定,假設該屬性指定為"and",當sql語句的開頭為"and",trim標籤將會去除該"and"

suffixoverrides

去除sql語句後面的關鍵字或者字元,該關鍵字或者字元由suffixoverrides屬性指定

下面使用幾個例子來說明trim標籤的使用。

有這樣的乙個例子:

<

select id=

"findactivebloglike"

resulttype

="blog">

select

*from

blog

where

<

if test="state !=

null">

state =#

if>

<

if test="title !=

null">

and title like#

if>

<

if test="author !=

null

and author.name !=

null">

and author_name like#

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

if>

<

if test="title !=

null">

and title like

#

if>

<

if test="author !=

null

and author.name !=

null">

and author_name like

#

if>

where

>

select

>

trim標籤也可以完成相同的功能,寫法如下:

<

if test="state !=

null">

state =#

if>

<

if test="title !=

null">

and title like

#

if>

<

if test="author !=

null

and author.name !=

null">

and author_name like

#

if>

trim>

有如下的例子:

如果紅框裡面的條件沒有匹配上,sql語句會變成如下:

insert

into role(role_name,) values(rolename,)

插入將會失敗。

使用trim標籤可以解決此問題,只需做少量的修改,如下所示:

其中最重要的屬性是

suffixoverrides=","
表示去除sql語句結尾多餘的逗號.

mybatis trim標籤的使用

mybatis的trim標籤一般用於去除sql語句中多餘的and關鍵字,逗號,或者給sql語句前拼接 where set 以及 values 等字首,或者新增 等字尾,可用於選擇性插入 更新 刪除或者條件查詢等操作。以下是trim標籤中涉及到的屬性 屬性描述 prefix 給sql語句拼接的字首 s...

mybatis trim標籤的使用

mybatis的trim標籤一般用於去除sql語句中多餘的and關鍵字,逗號,或者給sql語句前拼接 where set 以及 values 等字首,或者新增 等字尾,可用於選擇性插入 更新 刪除或者條件查詢等操作。以下是trim標籤中涉及到的屬性 屬性 描述 prefix 給sql語句拼接的字首 ...

mybatis trim標籤的使用

mybatis的trim標籤一般用於去除sql語句中多餘的and關鍵字,逗號,或者給sql語句前拼接 where set 以及 values 等字首,或者新增 等字尾,可用於選擇性插入 更新 刪除或者條件查詢等操作。1 使用trim標籤去除多餘的and關鍵字 有這樣的乙個例子 select from...