今天,根據庫位類型查詢 庫位列表 出現問題。
當庫位類型functions傳值:0時,並沒有按照"0"進行帥選,而是查出了所有的數據。
-----實際執行的查詢---
select id id, shelf_order shelfOrder,functions functions,customer_id customerId,state state from location where state=1 and deleted=0;
---期望下面的查詢---
select id id, shelf_order shelfOrder,functions functions,customer_id customerId,state state from location where state=1 and deleted=0 and functions=0;
mapper.xml內容:
select id id, shelf_order shelfOrder,functions functions,customer_id customerId,state state from location
where state=1 and deleted=0
<if test="functions!=null and functions!=''">
and functions = #{functions}
</if>
改成下面:
select id id, shelf_order shelfOrder,functions functions,customer_id customerId,state state from location
where state=1 and deleted=0
<if test="functions!=null and (functions!='' or functions ==0)">
and functions = #{functions}
</if>
以前出現過類似的錯誤,但是又再次犯錯。特此記錄一下。
問題分析:
首先他會獲取兩個判斷對象的類型,當拿一個字符串和一個數字判斷的時候,因爲類型不一樣嘛,當Mybatis發現,這個字符串是可以轉換成數字的,那麼就會把這個字符串轉成數字,然後再和這個數字判斷。
那麼問題就來了,這個空字符串會轉換成什麼數字呢?
從源碼
OgnlOps.compareWithConversion
就可以看出,這個空字符串,是會被轉成0的.所以現在一切豁然開朗.
參考文章;