MyBatis模糊查詢mapper.xml的寫法
模糊查詢語句不建議使用${}的方式,還是建議采用MyBatis自帶的#{}方式,#{}是預加載的方式運行的,比較安全,${}方式可以用但是有SQL注入的風險!!!
1.直接傳參
在controller類中
1
2
3
|
String id = "%"+ id +"%"; String name = "%"+ name +"%"; dao.selectByIdAndName(id,name); |
在mapper.xml映射文件中
1
2
3
|
< select > select * from table wherer id=#{id} or name like #{name} </ select > |
2.針對MySQL數據庫的語句
采用concat()函數,它可以將多個字符串連接成一個字符
1
2
3
|
< select > select * from table where name like concat('%',#{name},'%') </ select > |
3.適用于所有數據庫的則采用MyBatis的bind元素
1
2
3
4
5
|
public xx selectByLike(@Param("_name") String name); < select id = "selectByLike" > < bind name = "user_name" value = "'%' + _name + '%'" /> select * from table where name like #{user_name} </ select > |
其中_name為傳遞進來的參數,bind元素的value屬性將傳進來的參數和 '%' 拼接到一起后賦給name屬性的user_name,之后可以在select語句中使用user_name這個變量。
bind元素也支持傳遞多個參數
1
2
3
4
5
6
|
public xx selectByLike(@Param("_name") String name, @Param("_note") String note); < select id = "selectByLike" > < bind name = "user_name" value = "'%' + _name + '%'" /> < bind name = "user_note" value = "'%' + _note + '%'" /> select * from table where name like #{user_name} and note like #{user_note} </ select > |
MyBatis在xml中模糊查詢的常用的3種方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<!-- ******************** 模糊查詢的常用的3種方式:********************* --> < select id = "getUsersByFuzzyQuery" parameterType = "User" resultType = "User" > select < include refid = "columns" /> from users < where > <!-- 方法一: 直接使用 % 拼接字符串 注意:此處不能寫成 "%#{name}%" ,#{name}就成了字符串的一部分, 會發生這樣一個異常: The error occurred while setting parameters, 應該寫成: "%"#{name}"%",即#{name}是一個整體,前后加上% --> < if test = "name != null" > name like "%"#{name}"%" </ if > <!--方法二: 使用concat(str1,str2)函數將兩個參數連接 --> < if test = "phone != null" > and phone like concat(concat("%",#{phone}),"%") </ if > <!--方法三: 使用 bind 標簽,對字符串進行綁定,然后對綁定后的字符串使用 like 關鍵字進行模糊查詢 --> < if test = "email != null" > < bind name = "pattern" value = "'%'+email+'%'" /> and email like #{pattern} </ if > </ where > </ select > |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/a990914093/article/details/83743562