mybatis 標簽踩坑


 1   <update id="update">
 2         update bl_type
 3             <set>
 4                 <if test="typeName!=null and typeNmae!=''">
 5                     type_name = #{typeName},
 6                 </if>
 7                 <if test="typeBlogCount!=null and typeBlogCount!=''">
 8                     type_blog_count = #{typeBlogCount},
 9                 </if>
10                 <if test="enable!=null">
11                     enable = #{enable},
12                 </if>
13             </set>
14         where type_id = #{typeId}
15     </update>

使用mybatis 寫mapper.xml文件時,使用if標簽如:

 1 <if test="typeName!=null and typeNmae!=''"> 
這時如果傳入的參數為0的話會被忽略掉 無法正常的更新


使用if標簽的嵌套經測試也是會忽略參數0
 1    <update id="update">
 2         update bl_type
 3             <set>
 4                 <if test="typeName!=null">
 5                     <if test="typeName!=''">
 6                     type_name = #{typeName},
 7                     </if>
 8                 </if>
 9                 <if test="typeBlogCount!=null">
10                     <if test="typeBlogCount!=''">
11                     type_blog_count = #{typeBlogCount},
12                     </if>
13                 </if>
14                 <if test="enable!=null">
15                     enable = #{enable},
16                 </if>
17             </set>
18         where type_id = #{typeId}
19     </update>

如果if標簽判斷的是字段是否為空字符串也會忽略參數0

 1   <update id="update">
 2         update bl_type
 3             <set>
 4                     <if test="typeName!=''">
 5                     type_name = #{typeName},
 6                     </if>
 7                     <if test="typeBlogCount!=''">
 8                     type_blog_count = #{typeBlogCount},
 9                     </if>
10                 <if test="enable!=null">
11                     enable = #{enable},
12                 </if>
13             </set>
14         where type_id = #{typeId}
15     </update>

結論是if標簽只有如以下代碼時才不省略參數''0':

 1   <update id="update">
 2         update bl_type
 3             <set>
 4                 <if test="typeName!=null">
 5                     type_name = #{typeName},
 6                 </if>
 7                 <if test="typeBlogCount!=null">
 8                     type_blog_count = #{typeBlogCount},
 9                 </if>
10                 <if test="enable!=null">
11                     enable = #{enable},
12                 </if>
13             </set>
14         where type_id = #{typeId}
15     </update>

那么又有問題來了,如果前台傳來一個字符串時,某些字段就會被置為空字符串,這個怎么解決呢?

---------------------------------------更新-------------------------------------

問題已解決

為什么會出現這個問題?

因為在mybatis源碼中有將空字符串給轉換為0這個操作 所以我們傳入的參數'0'時就會被判斷與空字符串相等 所以if標簽的結果值為false

 

 

 參考資料:https://blog.csdn.net/Dongguabai/article/details/82981250

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM