这篇文章主要介绍了MyBatis的模糊查询mapper.xml的写法讲解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
这篇文章主要介绍了MyBatis的模糊查询mapper.xml的写法讲解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
这篇文章主要介绍了MyBatis的模糊查询mapper.xml的写法讲解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
模糊查询语句不建议使用${}的方式,还是建议采用MyBatis自带的#{}方式,#{}是预加载的方式运行的,比较安全,${}方式可以用但是有SQL注入的风险!!!
在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> |
采用concat()函数,它可以将多个字符串连接成一个字符
|
1
2
3
|
<select> select * from table where name like concat('%',#{name},'%')</select> |
|
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> |
|
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
发表评论