mybatis test把空字符串解析为0

旧城等待, 2021-11-09 09:01 355阅读 0赞

直接入主题:

一个mybatis的Mapper文件

xxxxMapper(Mapparams);

相关xml代码片段:

  1. <if test="packageType!= null and packageType!= '' or packageType == 0">
  2. and package\_type = \#\{packageType,jdbcType=TINYINT\}
  3. </if>

service端部分代码:

Mapparams = new HashMap<>();

params.put(“packageType”,””);

最初的设想,前端页面传入packageType条件为空字符串时,不把packageType作为过滤条件,但是上面的代码却达不到效果,下面从源码入手分析下为什么产生上述效果:

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

  1. protected Object evaluateGetValueBody(OgnlContext context, Object source)
  2. throws OgnlException
  3. \{
  4. context.setCurrentObject(source);
  5. context.setCurrentNode(this);
  6. if (!\_constantValueCalculated)
  7. \{
  8. \_constantValueCalculated = true;
  9. boolean constant = isConstant(context);
  10. if (constant)
  11. \{
  12. \_constantValue = getValueBody(context, source);
  13. \}
  14. \_hasConstantValue = constant;
  15. \}
  16. return \_hasConstantValue ? \_constantValue : getValueBody(context, source);
  17. \}

要找到原因不耐烦的话可以直接跳转到OgnlOps::compareWithConversion方法

  1. public static int compareWithConversion(Object v1, Object v2)
  2. \{
  3. int result;
  4. if (v1 == v2) \{
  5. result = 0;
  6. \} else \{
  7. int t1 = getNumericType(v1), t2 = getNumericType(v2), type = getNumericType(t1, t2, true);
  8. switch(type) \{
  9. case BIGINT:
  10. result = bigIntValue(v1).compareTo(bigIntValue(v2));
  11. break;
  12. case BIGDEC:
  13. result = bigDecValue(v1).compareTo(bigDecValue(v2));
  14. break;
  15. case NONNUMERIC:
  16. if ((t1 == NONNUMERIC) && (t2 == NONNUMERIC)) \{
  17. if ((v1 instanceof Comparable) && v1.getClass().isAssignableFrom(v2.getClass())) \{
  18. result = ((Comparable) v1).compareTo(v2);
  19. break;
  20. \} else \{
  21. throw new IllegalArgumentException("invalid comparison: " + v1.getClass().getName() + " and "
  22. + v2.getClass().getName());
  23. \}
  24. \}
  25. // else fall through
  26. case FLOAT:
  27. case DOUBLE:

double dv1 = doubleValue(v1),
dv2 = doubleValue(v2);

return (dv1 == dv2) ? 0 : ((dv1 < dv2) ? -1 : 1);

  1. default:
  2. long lv1 = longValue(v1),
  3. lv2 = longValue(v2);
  4. return (lv1 == lv2) ? 0 : ((lv1 < lv2) ? -1 : 1);
  5. \}
  6. \}
  7. return result;
  8. \}

最终会走到上面标红部分代码,而空字符串也会被转换成double的0.0,此时当空字符串时packageType!= null and packageType!= ‘’ or packageType == 0这个判断就会返回true,下面给出解决方案:

  1. <if test="packageType!= null and packageType!= '' or packageType == '0'.toString()">
  2. and package\_type = \#\{packageType,jdbcType=TINYINT\}
  3. </if>

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读