mybatis的xml中trim標籤有四個屬性
1.prefix 前綴增加的內容
2.suffix 後綴增加的內容
3.prefixOverrides 前綴需要覆蓋的內容,一般是第一個判斷條件前面的多餘的結構,如:第一個判斷條件前面多了 ‘and’
4.suffixOverrides 後綴需要覆蓋的內容,一般是最後一個數據的後面符號,如:set值的時候,最後一個值的後面多一個逗號‘,’
舉幾個例子:
1.根據用戶姓名和年齡查詢用戶,有什麼值就根據什麼條件(目的是說明幾個屬性用法,可能例子不適用於實際場景中)
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了。
再說說另兩個屬性,suffix和suffixOverrides。
如:更新用戶的信息,哪些字段有值就更新哪些字段,sql語句如下:
<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,純屬爲了說明四個屬性怎麼使用的,具體裏面的值會根據具體需求而定。希望舉一反三