mybatis處理查詢條件缺失的問題,原因是物件是int型
阿新 • • 發佈:2019-01-29
今天碰到一個很詭異的問題,後臺管理系統輸入了搜尋條件,查出來的資料不對,前端查出來37條,我用條件去資料庫查是12條。
然後列印執行的sql發現少了後面的條件。只帶了時間,沒有帶上城市id和小區id。下面是sql的where 條件的mybatis配置檔案:
<sql id="param"> where 1 = 1 <if test="res.start_date != null"> and c.open_time > #{res.start_date} </if> <if test="res.end_date != null"> <![CDATA[ and c.open_time < #{res.end_date} ]]> </if> <if test="res.city_id>0 and res.com_id=0"> and com.city_id = #{res.city_id} </if> <if test="res.city_id>0 and res.com_id>0"> and com.city_id = #{res.city_id} and com.id = #{res.com_id} </if> </sql>
Dao層相關程式碼片段是:
public List<CardRecord> paramList(@Param("res") Resident resident, @Param("limit") Limit limit);
然後我就懷疑取Resident物件中的city_id和com_id是空,不然怎麼執行的sql的where條件沒帶上。
除錯的時候檢視執行查詢之前的resident物件,是有值的。
接著看執行之後的結果:控制檯列印的sql還是沒有city_id和com_id的條件:
這就很奇怪了,為啥沒帶上。 這就要找問題所在了。
我首先先把時間條件註釋掉,看看結果:
那就是沒有時間條件,還是沒有city_id、com_id,那就是物件傳值過程中沒傳成功了。
我就想身為String物件的時間傳成功了,是不是問題出現在物件上,city_id和com_id都是int型的。
通過查資料才知道,原來是mybatis處理int型時,0判定為'',就是空,如果不能0,就不為空就好,大於0這種條件結果就是false了,改成這樣就可以了。搞定:)
<sql id="param"> where 1 = 1 <if test="res.start_date != null"> and c.open_time > #{res.start_date} </if> <if test="res.end_date != null"> <![CDATA[ and c.open_time < #{res.end_date} ]]> </if> <if test="res.city_id != null and res.com_id == null"> and com.city_id = #{res.city_id} </if> <if test="res.city_id != null and res.com_id != null"> and com.city_id = #{res.city_id} and com.id = #{res.com_id} </if> </sql>