解決mybatis where-if中if不能識別大寫AND,OR的問題
Caused by: org.apache.ibatis.ognl.ParseException: Encountered ' 'AND “” at line 1錯誤代碼:
<select resultMap='BaseResultMap'> SELECT ct.customer_name customerName,sam.city_code,sam.user_name,sam.account_name FROM sys_account_manager sam LEFT JOIN sys_customer ct ON ct.id = sam.customer_id WHERE sam.deleted = 0 <if test='customerName != null AND customerName != ’’ '> AND ct.customer_name LIKE concat(’%’,#{customerName},’%’) </if> <if test='cityCode != null AND cityCode != ’’ '> AND LOCATE(#{cityCode},sam.city_code) </if> order by status,account_validity_time DESC </select>正確代碼:
原因是:
if條件中AND為大寫,大寫不能識別,應改為小寫。
<select resultMap='BaseResultMap'> SELECT ct.customer_name customerName,sam.city_code,sam.user_name,sam.account_name FROM sys_account_manager sam LEFT JOIN sys_customer ct ON ct.id = sam.customer_id WHERE sam.deleted = 0 <if test='customerName != null and customerName != ’’ '> AND ct.customer_name LIKE concat(’%’,#{customerName},’%’) </if> <if test='cityCode != null and cityCode != ’’ '> AND LOCATE(#{cityCode},sam.city_code) </if> order by status,account_validity_time DESC </select>
補充:Mybatis中if判斷遇到的坑
最近在項目開發(fā)的過程中,遇到了Mybatis的一個坑(也許是Mybatis有意這樣設計的),對于Integer或者Long這種引用數據類型,在做if判斷的時候,如果引用數據類型為0,則mybatis將會視為”“空字符串,所以走不進判斷邏輯里。
以下余額字段為Long類型,availableAmount值為0時,將走不進判斷方法內的示例截圖:
在test判斷條件中添加”or availableAmount==0“即可,以下是示例截圖:
或者在業(yè)務場景允許的情況下,只判斷availableAmount!=null
<if test='availableAmount!=null'> ...</if>
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
