MyBatis參數條件查詢傳入的值為0時的判斷


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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM