mybatis <if test=““></if>标签0为null 无效的 踩坑

采过一个坑,写篇日志来记录下

<if test="orderStatus != null and orderStatus !=''">
    and t.is_ship=#{orderStatus}
</if>

当状态值设置为0时,操作完了,数据库没反应,没有设置为0
把状态用1和2表示,不使用0,一切正常,问题消失了。

MyBatis的表达式是用OGNL处理的。OGNL表达式的规则如下

Interpreting Objects as Booleans
Any object can be used where a boolean is required. OGNL interprets objects as booleans like this:
 
If the object is a Boolean, its value is extracted and returned;
 
If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false;
 
If the object is a Character, its boolean value is true if and only if its char value is non-zero;
 
Otherwise, its boolean value is true if and only if it is non-null.

根据这一条If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false

state !=‘’  传入0时,表达式的值为false;所以不执行。
解决办法,把这个删掉就可以了。

<if test="state != null">
	state = #{state }
</if>

本来只有String类型的才会进行这样的判断——xx!= ‘’,其实是自己码代码时只顾自制粘贴,自己给自己埋了个坑。

这里有必要再提一个“坑”,如果类似于String str =”A”; 这样的写法时时,根据第三条规则,OGNL将会识别为Java 中的 char类型,显然String 类型与char类型做==运算会返回false,从而导致表达式不成立。解决方法很简单,修改为

<if test='str!= null and str == "A"'>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段MyBatis XML中的SQL语句看起来已经比较优化了,但还有一些可以改进的地方。下面是一些建议: 1. 使用`<trim>`标签:在`<set>`标签中,每个`<if>`标签都会生成一个逗号,最后一个`<if>`标签需要特殊处理。可以使用`<trim>`标签来解决这个问题,示例代码如下: ```xml <set> <trim suffixOverrides="," suffix=" "> <if test="permission_id!=null"> permission_id = #{permission_id}, </if> <if test="pid!=null"> pid = #{pid}, </if> <!-- 其他属性 --> <if test="system_id!=null"> system_id = #{system_id} </if> </trim> </set> ``` 上面的代码中,使用了`suffixOverrides`属性来删除每个`<if>`标签生成的逗号。同时,使用了`suffix`属性来在最后一个属性后面添加一个空格。 2. 使用`<foreach>`标签:如果要更新的字段比较多,可以使用`<foreach>`标签来生成`<if>`标签,减少重复代码。示例代码如下: ```xml <set> <foreach collection="updateFields" item="field"> <if test="field=='permission_id'"> permission_id = #{permission_id}, </if> <if test="field=='pid'"> pid = #{pid}, </if> <!-- 其他属性 --> <if test="field=='system_id'"> system_id = #{system_id} </if> </foreach> </set> ``` 上面的代码中,`updateFields`是一个`List<String>`类型的变量,存储需要更新的字段名。使用`<foreach>`标签遍历`updateFields`,生成对应的`<if>`标签。 3. 使用动态SQL:如果更新的条件和更新的字段都不确定,可以使用动态SQL来生成SQL语句。示例代码如下: ```xml <update id="updatePermission" parameterType="Map"> UPDATE sys_permission <set> <foreach collection="updateFields" item="field"> ${field} = #{${field}}, </foreach> </set> <where> 1=1 <foreach collection="conditions" item="condition" separator="AND"> ${condition.field} ${condition.operator} #{condition.value} </foreach> </where> </update> ``` 上面的代码中,`updateFields`和`conditions`都是存储在`Map`中的变量,分别表示需要更新的字段和更新的条件。使用`${}`语法来插入动态SQL。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值