1. 程式人生 > 實用技巧 >mybatis <if>標籤踩坑

mybatis <if>標籤踩坑

 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>

那麼又有問題來了,如果前臺傳來一個字串時,某些欄位就會被置為空字串,這個怎麼解決呢?