MyBatis對動態SQL中使用trim標簽的場景及效果介紹比較少。
看起來有點難理解,簡單點來說--trim標簽有點類似於replace效果。
trim標簽有如下屬性:
prefix:前綴覆蓋並增加其內容
suffix:后綴覆蓋並增加其內容
prefixOverrides:前綴判斷的條件
suffixOverrides:后綴判斷的條件
通過百度以及自己測試:實踐是檢驗真理的唯一標准!
替代where標簽:
首先對UserMapper.xml中的SQL進行修改:
替代set標簽:(截圖有限,直接上代碼)
1 <update id="updateById"> 2 update sys_user 3 <trim prefix="SET" suffixOverrides="," suffix="where id =#{id}"> 4 <if test="userName != null and userName !=''"> 5 user_name =#{userName}, 6 </if> 7 <if test="userPassword != null and userPassword != ''"> 8 user_password =#{userPassword}, 9 </if> 10 <if test="userEmail != null and userEmail != ''"> 11 user_email =#{userEmail}, 12 </if> 13 <if test="userInfo != null and userInfo != ''"> 14 user_info =#{userInfo}, 15 </if> 16 <if test="headImg != null"> 17 head_img =#{headImg}, 18 </if> 19 <if test="createTime != null"> 20 create_time =#{createTime}, 21 </if> 22 id =#{id} 23 </trim> 24 </update>
這樣跟原來的where,set標簽一對比,其實也就是一個替代作用!
我不是很確認這種用法的具體場景,但是,就目前mybatis的動態sql語句來看的話,很多標簽都足夠用了。