java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis动态元素if使用

Mybatis动态元素if的使用方式

作者:三省同学

这篇文章主要介绍了Mybatis动态元素if的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

问题

代码

<if test="status != null and status != ''">
    AND status = #{status}
</if>

Mybatis动态元素if使用,上面写法适用于status类型为字符串。

若为整型,如int/Integer,当status为0时,就不会进入判断

解决

1:

<if test="status != null and status != '' or status == 0">
         AND u.status = #{status}
</if>

2

<if test="status != null">
         AND u.status = #{status}
</if>

源码阅读

查看SQL生成 

根据断点进入PageInterceptor

@Override
public Object intercept(Invocation invocation) throws Throwable {
    try {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        //由于逻辑关系,只会进入一次
        if (args.length == 4) {
            //4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            //6 个参数时
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        checkDialectExists();
        //对 boundSql 的拦截处理
        if (dialect instanceof BoundSqlInterceptor.Chain) {
            boundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.ORIGINAL, boundSql, cacheKey);
        }
        ...

进入MappedStatement查看SQL动态绑定

  public BoundSql getBoundSql(Object parameterObject) {
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings == null || parameterMappings.isEmpty()) {
      boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
    }
    ...

rootSqlNode.apply(context);这句代码很关键查看IF元素最终执行结果

@Override
public BoundSql getBoundSql(Object parameterObject) {
  DynamicContext context = new DynamicContext(configuration, parameterObject);
  rootSqlNode.apply(context);
  SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
  Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
  SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
  BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
  for (Map.Entry<String, Object> entry : context.getBindings().entrySet()) {
    boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
  }
  return boundSql;
}

循环动态元素节点

@Override
public boolean apply(DynamicContext context) {
  for (SqlNode sqlNode : contents) {
    sqlNode.apply(context);
  }
  return true;
}

在这里插入图片描述

进入类IfSqlNode

evaluator.evaluateBoolean(test, context.getBindings())如果为false就不会进入元素判断中

@Override
public boolean apply(DynamicContext context) {
  if (evaluator.evaluateBoolean(test, context.getBindings())) {
    contents.apply(context);
    return true;
  }
  return false;
}

判断逻辑

public class ExpressionEvaluator {

  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;
  }
  ...

进入类OgnlCache

public static Object getValue(String expression, Object root) {
  try {
    Map<Object, OgnlClassResolver> context = Ognl.createDefaultContext(root, new OgnlClassResolver());
    return Ognl.getValue(parseExpression(expression), context, root);
  } catch (OgnlException e) {
    throw new BuilderException("Error evaluating expression '" + expression + "'. Cause: " + e, e);
  }
}
protected Object evaluateGetValueBody(OgnlContext context, Object source) throws OgnlException {
     context.setCurrentObject(source);
     context.setCurrentNode(this);
     if (!this._constantValueCalculated) {
         this._constantValueCalculated = true;
         boolean constant = this.isConstant(context);
         if (constant) {
             this._constantValue = this.getValueBody(context, source);
         }

         this._hasConstantValue = constant;
     }

     return this._hasConstantValue ? this._constantValue : this.getValueBody(context, source);
 }
protected Object getValueBody(OgnlContext context, Object source) throws OgnlException {
    Object v1 = this._children[0].getValue(context, source);
    Object v2 = this._children[1].getValue(context, source);
    return OgnlOps.equal(v1, v2) ? Boolean.FALSE : Boolean.TRUE;
}
public static boolean equal(Object v1, Object v2) {
    if (v1 == null) {
        return v2 == null;
    } else if (v1 != v2 && !isEqual(v1, v2)) {
        if (v1 instanceof Number && v2 instanceof Number) {
            return ((Number)v1).doubleValue() == ((Number)v2).doubleValue();
        } else {
            return false;
        }
    } else {
        return true;
    }
}
public static boolean isEqual(Object object1, Object object2) {
    boolean result = false;
    if (object1 == object2) {
        result = true;
    } else if (object1 != null && object1.getClass().isArray()) {
        if (object2 != null && object2.getClass().isArray() && object2.getClass() == object1.getClass()) {
            result = Array.getLength(object1) == Array.getLength(object2);
            if (result) {
                int i = 0;

                for(int icount = Array.getLength(object1); result && i < icount; ++i) {
                    result = isEqual(Array.get(object1, i), Array.get(object2, i));
                }
            }
        }
    } else {
        result = object1 != null && object2 != null && (object1.equals(object2) || compareWithConversion(object1, object2) == 0);
    }

    return result;
}

关键代码

public static int compareWithConversion(Object v1, Object v2) {
       int result;
       if (v1 == v2) {
           result = 0;
       } else {
           int t1 = getNumericType(v1);
           int t2 = getNumericType(v2);
           int type = getNumericType(t1, t2, true);
           switch(type) {
           case 6:
               result = bigIntValue(v1).compareTo(bigIntValue(v2));
               break;
           case 9:
               result = bigDecValue(v1).compareTo(bigDecValue(v2));
               break;
           case 10:
               if (t1 == 10 && t2 == 10) {
                   if (v1 instanceof Comparable && v1.getClass().isAssignableFrom(v2.getClass())) {
                       result = ((Comparable)v1).compareTo(v2);
                       break;
                   }

                   throw new IllegalArgumentException("invalid comparison: " + v1.getClass().getName() + " and " + v2.getClass().getName());
               }
           case 7:
           case 8:
               double dv1 = doubleValue(v1);
               double dv2 = doubleValue(v2);
               return dv1 == dv2 ? 0 : (dv1 < dv2 ? -1 : 1);
           default:
               long lv1 = longValue(v1);
               long lv2 = longValue(v2);
               return lv1 == lv2 ? 0 : (lv1 < lv2 ? -1 : 1);
           }
       }

       return result;
   }
public static double doubleValue(Object value) throws NumberFormatException {
   if (value == null) {
       return 0.0D;
   } else {
       Class c = value.getClass();
       if (c.getSuperclass() == Number.class) {
           return ((Number)value).doubleValue();
       } else if (c == Boolean.class) {
           return (Boolean)value ? 1.0D : 0.0D;
       } else if (c == Character.class) {
           return (double)(Character)value;
       } else {
       		// 原因就这了!!!
           String s = stringValue(value, true);
           return s.length() == 0 ? 0.0D : Double.parseDouble(s);
       }
   }
}

为什么为0时,进不去

结论:

从断点跟进源码得出,当!=null条件是,Mybatis会把传进去的值与null比较,0.0==null为false,当比较空字符""时,会先把空字符进行一次转化doubleValue(v2),结果为0.0。

所以当status是整型且为0时,就不会进入判断

重要源码节点

SimpleNode::getValue—>SimpleNode::evaluateGetValueBody—>ASTEq::getValueBody—>OgnlOps::equal—>OgnlOps::compareWithConversion

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文