直接入主题:
一个mybatis的Mapper文件
xxxxMapper(Map<String,Object>params);
相关xml代码片段:
<if test="packageType!= null and packageType!= '' or packageType == 0">
and package_type = #{packageType,jdbcType=TINYINT}
</if>
service端部分代码:
Map<String,Object>params = new HashMap<>();
params.put("packageType","");
最初的设想,前端页面传入packageType条件为空字符串时,不把packageType作为过滤条件,但是上面的代码却达不到效果,下面从源码入手分析下为什么产生上述效果:
SimpleNode::getValue -->SimpleNode::evaluateGetValueBody-->ASTEq::getValueBody-->OgnlOps::equal-->OgnlOps::compareWithConversion
protected Object evaluateGetValueBody(OgnlContext context, Object source)
throws OgnlException
{
context.setCurrentObject(source);
context.setCurrentNode(this);
if (!_constantValueCalculated)
{
_constantValueCalculated = true;
boolean constant = isConstant(context);
if (constant)
{
_constantValue = getValueBody(context, source);
}
_hasConstantValue = constant;
}
return _hasConstantValue ? _constantValue : getValueBody(context, source);
}
要找到原因不耐烦的话可以直接跳转到OgnlOps::compareWithConversion方法
public static int compareWithConversion(Object v1, Object v2)
{
int result;
if (v1 == v2) {
result = 0;
} else {
int t1 = getNumericType(v1), t2 = getNumericType(v2), type = getNumericType(t1, t2, true);
switch(type) {
case BIGINT:
result = bigIntValue(v1).compareTo(bigIntValue(v2));
break;
case BIGDEC:
result = bigDecValue(v1).compareTo(bigDecValue(v2));
break;
case NONNUMERIC:
if ((t1 == NONNUMERIC) && (t2 == NONNUMERIC)) {
if ((v1 instanceof Comparable) && v1.getClass().isAssignableFrom(v2.getClass())) {
result = ((Comparable) v1).compareTo(v2);
break;
} else {
throw new IllegalArgumentException("invalid comparison: " + v1.getClass().getName() + " and "
+ v2.getClass().getName());
}
}
// else fall through
case FLOAT:
case DOUBLE:
double dv1 = doubleValue(v1),
dv2 = doubleValue(v2);
return (dv1 == dv2) ? 0 : ((dv1 < dv2) ? -1 : 1);
default:
long lv1 = longValue(v1),
lv2 = longValue(v2);
return (lv1 == lv2) ? 0 : ((lv1 < lv2) ? -1 : 1);
}
}
return result;
}
最终会走到上面标红部分代码,而空字符串也会被转换成double的0.0,此时当空字符串时packageType!= null and packageType!= '' or packageType == 0这个判断就会返回true,下面给出解决方案:
<if test="packageType!= null and packageType!= '' or packageType == '0'.toString()">
and package_type = #{packageType,jdbcType=TINYINT}
</if>