mybatis的xml中trim標簽有四個屬性
1.prefix
前綴增加的內容
2.suffix
后綴增加的內容
3.prefixOverrides
前綴需要覆蓋的內容,一般是第一個判斷條件前面的多余的結構,如:第一個判斷條件前面多了 ‘and'
4.suffixOverrides
后綴需要覆蓋的內容,一般是最后一個數據的后面符號,如:set值的時候,最后一個值的后面多一個逗號‘,'
舉幾個例子:
1.根據用戶姓名和年齡查詢用戶,有什么值就根據什么條件(目的是說明幾個屬性用法,可能例子不適用于實際場景中)
1
2
3
4
5
6
7
8
9
10
11
12
|
select * from User where name = 'zhangsan' and age= '20' ; < select id= 'queryUser' > select * from User <trim prefix= 'where' prefixOverrides= 'and' > <if test= "name != null and name != ''" > name = #{ name } </if> <if test= "age !=null and age !=''" > and age = #{age} </if> </trim> < select > |
上面例子是很常規的一個寫法,第一個條件前面沒有任何符號,第二個條件要加上and,否則sql語句會報錯。很理想的狀態是第一個和第二個都有值,但是既然判斷,說明也可能會沒有值,當第一個name沒有值的時候,這個時候sql語句就會是
select * from User where and age='',很明顯這個sql語句語法存在問題。在這里標簽屬性prefixOverrides就起作用了,它會讓前綴where覆蓋掉第一個and。覆蓋之后的是:select * from User where age='';
前綴加上where就不說,因為屬性 prefix='where',這個where 也可以寫在<trim>標簽的外面,這樣此處就無需用到屬性prefix了。
現在有更方便的標簽了,就是<where>,用這個標簽效果一樣的,會忽略掉第一個符合條件前面的符號。
1
2
3
4
5
6
7
8
9
|
select * from User < where > <if test= "name != null and name != ''" > name = #{ name } </if> <if test= "age !=null and age !=''" > and age = #{age} </if> </ where > |
如果第一個name值是null,則age前面的and會被忽略掉。
再說說另兩個屬性,suffix和suffixOverrides。
如:更新用戶的信息,哪些字段有值就更新哪些字段,sql語句如下:
1
2
3
4
5
6
7
8
9
10
11
|
< update id= "updateUser" > update User <trim prefix= "set" suffixOverrides= "," suffix= "where id='1'" > <if test= "name != null and name != ''" > name =#{ name }, </if> <if test= "age != null and age !=''" > age=#{age}, </if> </trim> </ update > |
本例中最后一個條件中的逗號“,”會被后綴覆蓋掉,本例中的后綴是where id =‘1';
OK,純屬為了說明四個屬性怎么使用的,具體里面的值會根據具體需求而定。希望舉一反三~
trim標簽的使用場景
使用trim標簽去除多余的逗號
如果紅框里面的條件沒有匹配上,sql語句會變成如下:
1
|
INSERT INTO role(role_name,) VALUES (roleName,) |
插入將會失敗。
做如下修改:
其中最重要的屬性是
1
|
suffixOverrides= "," |
表示去除sql語句結尾多余的逗號.
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/chenpuzhen/article/details/89643861