关于MyBatis模糊查询的几种实现方式
作者:柚子猫屿 时间:2023-05-09 04:23:12
一、模糊查询的几种实现方式
1.concat函数和#{}拼接的方式
student_name like concat('%',#{studentName},'%')
2.%和${}拼接的方式
student_name like '%${studentName}%'
3.concat函数和${}拼接的方式
student_name like concat('%','${studentName}','%')
4.||和#{}拼接的方式
student_name like '%'||#{studentName}||'%'
分析: (1)${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中,可能引发sql注入。 (2)#{ }是预编译处理,MyBatis在处理#{ }时,它会将sql中的#{ }替换为?,然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号,使用占位符的方式提高效率,可以防止sql注入。因此最好使用#{ }方式。 (3)concat函数最好不要使用,最好使用||,因为在Oracle中,concat()只能对两个字符串进行拼接(字符串多的话只能嵌套使用),而||可以对字符串无限拼接。
5.建议使用的方式
建议使用第四种哦,示例:
<if test="studentName != null and studentName !=''">
and student_name like '%'||#{studentName}||'%'
</if>
二、用mybatis出现的一些问题
1.一般查询条件的使用
在mapper文件里面关于查询if的条件基本都要写出两种空值,否则就会在查询时把其他不需要的数据也查出来。
错误示范:
<if test="studentName != null">
and student_name = #{studentName}
</if>
正确示范:
<if test="studentName != null and studentName !=''">
and student_name = #{studentName}
</if>
2.日期查询条件的使用
这个是在写日期查询条件时,出现了日期只能修改,但不能为空的问题:
错误示范:
<if test="effDate != null and effDate !=''">
and eff_date = #{effDate}
</if>
<if test="expDate != null and expDate !=''">
and exp_date = #{expDate}
</if>
正确示范:去掉外面的if判空条件
and eff_date = #{effDate}
and exp_date = #{expDate}
3.排序问题
查询时最好按id倒序,在修改之后不影响原有顺序
比如:order by student_id desc
来源:https://blog.csdn.net/qq_41861832/article/details/128243734
标签:MyBatis,查询,模糊
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
maven profile动态选择配置文件详解
2023-11-05 22:05:20
![](https://img.aspxhome.com/file/2023/4/64514_0s.png)
Mybatis配置错误:java.lang.ExceptionInInitializerError
2021-12-31 16:58:59
![](https://img.aspxhome.com/file/2023/4/77114_0s.jpg)
c# 使用模式匹配以及 is 和 as 运算符安全地进行强制转换
2022-11-23 09:47:51
SpringBoot整合Mybatis-plus案例及用法实例
2022-03-31 12:02:44
Android Studio Menu选择菜单的建立方法
2023-07-28 03:46:31
![](https://img.aspxhome.com/file/2023/4/85454_0s.png)
微信小程序 springboot后台如何获取用户的openid
2023-01-13 17:07:42
JAVA实现基于Tcp协议的简单Socket通信实例
2022-07-07 21:44:36
![](https://img.aspxhome.com/file/2023/1/99761_0s.jpg)
解决WPF附加属性的Set函数不调用的问题
2022-09-27 09:52:38
C#后台创建控件并获取值的方法
2022-10-20 08:39:46
C# 创建控制台应用程序
2023-10-09 07:27:37
![](https://img.aspxhome.com/file/2023/7/108757_0s.png)
Android组件Glide实现图片平滑滚动效果
2022-02-24 22:53:14
![](https://img.aspxhome.com/file/2023/2/101832_0s.jpg)
Android实战教程第一篇之最简单的计算器
2023-03-12 17:57:54
![](https://img.aspxhome.com/file/2023/9/138439_0s.jpg)
Android蓝牙库FastBle的基础入门使用
2021-09-21 07:34:21
Java实现在线SQL编程最新完整版
2022-04-12 01:03:45
深入Android 五大布局对象的应用
2022-03-23 15:25:15
![](https://img.aspxhome.com/file/2023/7/93337_0s.jpg)
结合mybatis-plus实现简单不需要写sql的多表查询
2021-06-25 12:54:22
JAVA复制数组和重置数组大小操作
2021-08-29 02:02:41
![](https://img.aspxhome.com/file/2023/1/64751_0s.jpg)
MyBatis分页插件PageHelper的使用与原理
2021-06-15 09:24:35
![](https://img.aspxhome.com/file/2023/5/101985_0s.png)
java Lock接口详解及实例代码
2022-12-15 21:44:38
C#中获取二维数组的行数和列数以及多维数组各个维度的长度
2022-08-06 12:08:55