MyBatis模糊查询的几种实现方式

编程入门 行业动态 更新时间:2024-10-11 11:18:36

MyBatis模糊查询的<a href=https://www.elefans.com/category/jswz/34/1769370.html style=几种实现方式"/>

MyBatis模糊查询的几种实现方式

大家好呀,我是柚子,今天这篇文章总结MyBatis模糊查询的几种实现方式~

文章目录

  • 前言
  • 一、模糊查询的几种实现方式
    • 1.concat函数和#{}拼接的方式
    • 2.%和${}拼接的方式
    • 3.concat函数和${}拼接的方式
    • 4.||和#{}拼接的方式
    • 5.建议使用的方式
  • 二、用mybatis出现的一些问题
    • 1.一般查询条件的使用
    • 2.日期查询条件的使用
    • 3.排序问题
  • 总结


前言

柚子今年才开始写博客,今天对以前笔记有关MyBatis模糊查询的几种实现方式进行一番总结~


提示:以下是本篇文章正文内容,下面案例可供参考

一、模糊查询的几种实现方式

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

总结

以上就是今天要讲的内容,本文仅仅简单介绍了MyBatis模糊查询的几种实现方式,和应用中遇到的问题,希望对大家有所帮助。


╭◜◝ ͡ ◜◝╮
( ˃̶͈◡˂ ̶͈ )感觉有用的话,欢迎点赞评论呀!
╰◟◞ ͜ ◟◞╯

更多推荐

MyBatis模糊查询的几种实现方式

本文发布于:2024-03-04 19:14:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1710162.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几种   模糊   方式   MyBatis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!