程序员技术干货

Mybatis: sql中if 判断的坑

2016-11-24  本文已影响914人  voltric

“原创精选,转载注明出处,三克油”

前言

正文

<if test="name !=null and name !='' ">
    name = #{name},
</if>
<if test="sex !=null">
    sex = #{sex},
</if>
  1. 首先在mbatis中找到啊以上包路径、此路径为解析script标签时用到的类
org.apache.ibatis.scripting
  1. 过程不在细说、对于mbatis来说、script标签的动态SQL、都是遍历条件做SQL拼接而成的
  2. 我们直接看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;
}
  1. 再具体看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;
}
  1. 由此可以发现、当动态sql参数是int类型、并且传入0时、是使用OgnlCache获取的value、而OgnlCache是对OGNL的封装
  2. OGNL的官网上面可以看到如下解释
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.

结尾

For Future.

上一篇 下一篇

猜你喜欢

热点阅读