MyBatis條件查詢對字段判斷是否為空一般為:
<if test="testValue!=null and testValue != ''">
and test_value = #{testValue}
</if>
如果傳入參數為Integer類型且值為0時,會把0轉為空串
源碼真實情況是:
MyBatis解析的所有sqlNode節點,針對if節點會交給IfSqlNode來處理,進過層層處理,最終都會調用OgnlOps.class類的doubleValue(Object value)方法
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).booleanValue() ? 1.0D : 0.0D;
} else if (c == Character.class) {
return (double)((Character)value).charValue();
} else {
String s = stringValue(value, true);
return s.length() == 0 ? 0.0D : Double.parseDouble(s);
}
}
}
0和""都調用該方法返回的double值都為0.0,在進行比較。
處理方法:
<if test="testValue!=null and testValue!='' or 0 == testValue">
and test_value = #{testValue}
</if>
或者
<if test="testValue!=null">
and test_value = #{testValue}
</if>