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>

那么又有问题来了,如果前台传来一个字符串时,某些字段就会被置为空字符串,这个怎么解决呢?

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

问题已解决

为什么会出现这个问题?

因为在mybatis源码中有将空字符串给转换为0这个操作 所以我们传入的参数'0'时就会被判断与空字符串相等 所以if标签的结果值为false

 

 

 参考资料:https://blog.csdn.net/Dongguabai/article/details/82981250

 

posted @ 2020-08-10 22:26  oops_w  阅读(743)  评论(0编辑  收藏  举报