一、注意事项
在使用<if test </if>标签的时候,判断空字符串时需要注意的是 ""==0
例如sql
<!-- 根据性别查询学生 -->
<select id="selectByGender" parameterType="string" resultMap="StudentResultMap">
SELECT <include refid="baseColumns"/>
FROM <include refid="tableName"/>
WHERE 1 = 1
<if test="gender != null and gender == 0">
AND gender = '男'
</if>
<if test="gender != null and gender != ''">
AND gender = '女'
</if>
</select>
当gender不进行传值的时候即 gender为"" 时会走第一个判断,执行的sql为
SELECT
id, name, age, gender, email, phone, address, create_time, update_time
FROM student
WHERE 1 = 1
AND gender = '男'
二、关键debug过程
2.1.入口断点
StudentServiceImpl

2.2.mybatis待转换sql
org.apache.ibatis.executor包下CachingExecutor类中query方法
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler)
throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameterObject);
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

ms中第五个参数


2.3.组合后sql
BoundSql boundSql = ms.getBoundSql(parameterObject);
SELECT
id, name, age, gender, email, phone, address, create_time, update_time
FROM student
WHERE 1 = 1
AND gender = '男'

2.4.getBoundSql方法判断if标签
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);
}
// check for nested result maps in parameter mappings (issue #30)
for (ParameterMapping pm : boundSql.getParameterMappings()) {
String rmId = pm.getResultMapId();
if (rmId != null) {
ResultMap rm = configuration.getResultMap(rmId);
if (rm != null) {
hasNestedResultMaps |= rm.hasNestedResultMaps();
}
}
}
return boundSql;
}
getBoundSql方法中rootSqlNode.apply(context);
@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);
context.getBindings().forEach(boundSql::setAdditionalParameter);
return boundSql;
}
org.apache.ibatis.scripting.xmltags包下MixedSqlNode类中node.apply(context)方法
@Override
public boolean apply(DynamicContext context) {
contents.forEach(node -> node.apply(context));
return true;
}
package org.apache.ibatis.scripting.xmltags包下StaticTextSqlNode类中apply方法会将rootSqlNode中的所有内容进行判断并组合成sql
@Override
public boolean apply(DynamicContext context) {
context.appendSql(text);
return true;
}
逐步组合sql
public void appendSql(String sql) {
sqlBuilder.add(sql);
}
如果是IfSql则在org.apache.ibatis.scripting.xmltags包下的apply进行判断并拼接sql
@Override
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方法
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)).compareTo(BigDecimal.ZERO) != 0;
}
return value != null;
}
public static Object getValue(String expression, Object root) {
try {
OgnlContext context = Ognl.createDefaultContext(root, MEMBER_ACCESS, CLASS_RESOLVER, null);
return Ognl.getValue(parseExpression(expression), context, root);
} catch (OgnlException e) {
throw new BuilderException("Error evaluating expression '" + expression + "'. Cause: " + e, e);
}
}
判断以下条件是否为ture
gender != null and gender == 0

public static OgnlContext addDefaultContext(Object root, MemberAccess memberAccess, ClassResolver classResolver, TypeConverter converter, OgnlContext initialContext) {
OgnlContext result = new OgnlContext(memberAccess, classResolver, converter, initialContext);
result.setRoot(root);
if (initialContext != null) {
result.putAll(initialContext);
}
return result;
}
public static Object getValue(Object tree, OgnlContext context, Object root) throws OgnlException {
return getValue(tree, context, root, null);
}

这个判断结果为true,则将AND条件
AND gender = '男'
添加到sql后面


2.5.解读下getValue方法
public static Object getValue(String expression, Object root) {
try {
OgnlContext context = Ognl.createDefaultContext(root, MEMBER_ACCESS, CLASS_RESOLVER, null);
return Ognl.getValue(parseExpression(expression), context, root);
} catch (OgnlException e) {
throw new BuilderException("Error evaluating expression '" + expression + "'. Cause: " + e, e);
}
}
private static Object parseExpression(String expression) throws OgnlException {
Object node = expressionCache.get(expression);
if (node == null) {
node = Ognl.parseExpression(expression);
expressionCache.put(expression, node);
}
return node;
}
返回true
public static Object getValue(Object tree, OgnlContext context, Object root) throws OgnlException {
return getValue(tree, context, root, null);
}
返回true
public static Object getValue(Object tree, OgnlContext context, Object root, Class<?> resultType) throws OgnlException {
Object result;
Node node = (Node) tree;
if (node.getAccessor() != null) {
result = node.getAccessor().get(context, root);
} else {
result = node.getValue(context, root);
}
if (resultType != null) {
result = getTypeConverter(context).convertValue(context, root, null, null, result, resultType);
}
return result;
}
返回true
protected Object getValueBody(OgnlContext context, Object source)
throws OgnlException {
Object result = null;
int last = children.length - 1;
for (int i = 0; i <= last; ++i) {
result = children[i].getValue(context, source);
if (i != last && !OgnlOps.booleanValue(result))
break;
}
return result;
}
public final Object getValue(OgnlContext context, Object source)
throws OgnlException {
Object result = null;
if (context.isTraceEvaluations()) {
EvaluationPool pool = OgnlRuntime.getEvaluationPool();
Throwable evalException = null;
Evaluation evaluation = pool.create(this, source);
context.pushEvaluation(evaluation);
try {
result = evaluateGetValueBody(context, source);
} catch (OgnlException | RuntimeException ex) {
evalException = ex;
throw ex;
} finally {
Evaluation eval = context.popEvaluation();
eval.setResult(result);
if (evalException != null) {
eval.setException(evalException);
}
}
} else {
result = evaluateGetValueBody(context, source);
}
return result;
}
evaluateGetValueBody方法返回 true
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);
}
org.apache.ibatis.ognl 包下 ASTEq 类 getValueBody 方法,v1 值为 "",v2值为0
protected Object getValueBody(OgnlContext context, Object source) throws OgnlException {
Object v1 = children[0].getValue(context, source);
Object v2 = children[1].getValue(context, source);
return OgnlOps.equal(v1, v2) ? Boolean.TRUE : Boolean.FALSE;
}
org.apache.ibatis.ognl 包下 OgnlOps 类 equal方法 v1值为"",调用isEqual方法
public static boolean equal(Object v1, Object v2) {
if (v1 == null) return v2 == null;
return v1 == v2 || isEqual(v1, v2);
}
org.apache.ibatis.ognl 包下 OgnlOps 类 isEqual 方法
public static boolean isEqual(Object object1, Object object2) {
boolean result = false;
if (object1 == object2) {
result = true;
} else if (object1 != null && object2 != null) {
if (object1.getClass().isArray()) {
if (object2.getClass().isArray() && (object2.getClass() == object1.getClass())) {
result = (Array.getLength(object1) == Array.getLength(object2));
if (result) {
for (int i = 0, icount = Array.getLength(object1); result && (i < icount); i++) {
result = isEqual(Array.get(object1, i), Array.get(object2, i));
}
}
}
} else {
int t1 = getNumericType(object1);
int t2 = getNumericType(object2);
// compare non-comparable non-numeric types by equals only
if (t1 == NONNUMERIC && t2 == NONNUMERIC && (!(object1 instanceof Comparable) || !(object2 instanceof Comparable))) {
result = object1.equals(object2);
} else {
result = compareWithConversion(object1, object2) == 0;
}
}
}
return result;
}
org.apache.ibatis.ognl 包下 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 if ((v1 instanceof Enum<?> && v2 instanceof Enum<?>) &&
(v1.getClass() == v2.getClass() || ((Enum) v1).getDeclaringClass() == ((Enum) v2).getDeclaringClass())) {
result = ((Enum) v1).compareTo((Enum) 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;
}
这个方法入参""和0 比较时返回结果为0

isEqual方法中,将compareWithConversion方法的返回值0 和 0 进行比较,返回true

2.6.debug总结
核心逻辑就是isEqual方法执行的时候走了double分支将""转换成了0.0,将0转换成了0.0
所以:if标签时如果参数为"" 时如果和0 进行==比较返回true
三、仓库地址和代码信息
3.1.代码仓库路径,项目名称demo-springboot-mybatis
https://gitee.com/qiuxiaodong/demo.git
3.2.接口请求地址
http://127.0.0.1:8081/demo/conditionIfTest?gender=
3391




被折叠的 条评论
为什么被折叠?



