好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MyBatis的模糊查询mapper.xml的写法讲解

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

查看更多关于MyBatis的模糊查询mapper.xml的写法讲解的详细内容...

  阅读:29次