1. 程式人生 > >關於mybatis中llike模糊查詢中#和$的使用

關於mybatis中llike模糊查詢中#和$的使用

在mybatis中經常要寫到like 查詢,以前從來沒有遇到什麼問題,突然遇到一個問題,找了好長時間沒找到,最後找到了,是關於#和$的使用的,總結如下:

name like  表示式    and    falg=#{falg}

本次示例中共兩個條件,一個是name  like  表示式, 還有flag相等,這個是使用#{}佔位符,沒有任何問題,關鍵問題就是 表示式的書寫.下面來研究下表達式的書寫:

如果寫成'%#{name}%' ,就會報錯Parameter index out of range (2> number of parameters, which is 1). 這個錯誤,就是引數的問題,所以就查閱了一下資料,然後結合自己的實踐,得到總結如下:

本次使用 mysql 5.5.27和mybatis3.2.7進行測試

1.表示式: name like"%"#{name}"%"

==>  Preparing: select * from bbs_brand WHERE namelike"%"?"%"and falg=? limit 0 , 10

==>Parameters: (String), 1(Integer)

能夠查詢出來,沒有問題,這是使用了佔位符來佔位,寫成SQL就是: name like "%"''"%"沒有問題

2.表示式: name like '%${name}%'

Preparing:select count(0) from (select * from bbs_brand WHERE name like'%

%' and falg=?) as total

Parameters: 1(Integer)

使用$進行字串的拼接,直接把傳入的值,拼接上去了,沒有任何問題

3. 表示式: name likeconcat(concat('%',#{username}),'%')

==>  Preparing: select count(0) from (select *from bbs_brand WHERE name like

concat(concat('%',?),'%') and falg=?) as total

==>Parameters: (String), 1(Integer)

這是使用了cancat進行字串的連線,同時使用了#進行佔位

轉換成SQL就是: name like CONCAT(CONCAT('%',''),'%')

3. 表示式:name like CONCAT('%','${name}','%')

==>  Preparing: select count(0) from (select *from bbs_brand WHERE name likeCONCAT('%','','%') and falg=?) astotal

==>Parameters: 1(Integer)

對上面的表示式進行了簡化,更方便了

4. 表示式:name like '%'||#{name}||'%'

這個不能滿足要求,直接把資料庫中的所有資料查詢出來了,不符合我的要求,mysql||代表是or的意思

==>  Preparing: select count(0) from (select *from bbs_brand WHERE name like'%'||?||'%' and falg=?) as total

==>Parameters: (String), 1(Integer)

關於$和#使用的第二個問題:

介面中方法:void deleteBrandByIds(@Param("ids")String  ids);
xml中:<!-- brand delete  -->

<delete id="deleteBrandByIds">
         <!-- update bbs_brand set is_display=0 where id IN (#{ids}) -->

update bbs_brand set is_display=0 where id IN (${ids})

這裡只能夠使用$ 進行字串的拼接,而不是#.
當我們傳入的字串是1,3,5,7的時候,用#只能刪除id為1的品牌,其他的就不能刪除了,這是因為,使用了#,就是一個佔位符了,經過編譯後是
where id in(?)   加入字串後是 where id in('1,3,5,7') 這種,在SQL中就只會刪除一個,我們來看SQL的執行效果

 

也是隻是刪除一條記錄的,

所以如果想使用#,請在xml中使用動態的SQL,,傳遞的引數使用List<String>來進行迴圈遍歷.

2018年9月18日11:06:37更新:

貌似上面有一些方法在mybatis更換了版本就失效的問題,

我們可以在service中拼接字串,

StringBuilder sb = new StringBuilder("%");
sb.append(key);
sb.append("%");

把這個sb傳遞到dao中去,在xml中直接寫成:

where ext_name like #{key}

就可以查詢到爭取的結果