问题
我们一般在Mbatis中做update更新时、都会加上使用if test判断、防止更新空值、一般正常都是像name这种既判断NULL又判断’’
但是对于int类型的sex字段、如果加上 status != ''条件时、当status值为0时、此sql不会被拼加上、也不会被执行更新
<if test="name !=null and name !='' ">
name = #{name},
</if>
<if test="status !=null">
status = #{status},
</if>
解答
- 看一下Mbatis源码
- mbatis中此路径为解析script标签时用到的类
org.apache.ibatis.scripting
- 对于mbatis来说、script标签的动态SQL、都是遍历条件做SQL拼接而成的
- 我们直接看org.apache.ibatis.scripting.xmltags.IfSqlNode这个类、此类是script标签中if标签的判断方式、其中evaluateBoolean返回true时、if标签下的SQL拼接生效
public boolean apply(DynamicContext context) {if (evaluator.evaluateBoolean(test, context.getBindings())) {
contents.apply(context);return true;}return false;
}
- 再看org.apache.ibatis.scripting.xmltags.ExpressionEvaluator :evaluateBoolean 这个方法、我们看到了如果是number类型、会与0做判断比较
public boolean evaluateBoolean(String expression, Object parameterObject) {
Object value = OgnlCache.getValue(expression, parameterObject);if (value instanceof Boolean) return (Boolean) value;if (value instanceof Number) return !new BigDecimal(String.valueOf(value)).equals(BigDecimal.ZERO);return value != null;
}
- 由此可以发现、当动态sql参数是int类型、并且传入0时、是使用OgnlCache获取的value、而OgnlCache是对OGNL的封装
- 在OGNL的官网上面可以看到如下解释
任何需要布尔值的对象都可以使用。OGNL将对象解释为布尔值,如下所示:
·如果对象是布尔值,则提取并返回其值;
·如果对象是Number,则将其双精度浮点值与零进行比较;非零视为真,零视为假;
·如果对象是Character,则其布尔值为true,当且仅当其char值为非零时;
否则,它的布尔值为true,当且仅当它不是null时。
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.