MyBatis 实现模糊查询 *Mapper.xml 的几种配置方式

版权声明:本文为博主原创文章,欢迎转载,转载请注明出处。觉得此文有用的,不嫌麻烦的,就留个言呐,或者点个赞呐,要是嫌麻烦呢,也麻烦点个赞嘛 https://blog.csdn.net/qq_40147863/article/details/88074591

MyBatis 实现模糊查询 *Mapper.xml 的几种配置方式

在学习 MyBatis 过程中想实现模糊查询,可惜失败了。后来上百度上查了一下,才解决了。记录一下 MyBatis 实现模糊查询 *Mapper.xml 的几种配置方式。

首先数据库表是这样的:
数据库表名为 user_info,初始化了几条记录,如图:

错误的方式:

然后它就挂了:
在这里插入图片描述

正确的配置方式

(1)使用 ${} 替换 #{}

<select id="searchName" resultType="map" parameterType="amp">
SELECT * FROM test_student where username LIKE '%${name}%'
</select>

注:使用${…}不能有效防止SQL注入,所以这种方式虽然简单但是不推荐使用!!!

(2)把 ‘%#{name}%’ 改为 “%” #{name} “%”

<select id="searchName" resultType="map" parameterType="amp">
SELECT * FROM test_student where username LIKE "%"#{name}"%"
</select>

(3)使用 sql 中的字符串拼接函数

<select id="searchName" resultType="map" parameterType="amp">
SELECT * FROM test_student where username LIKE CONCAT(CONCAT('%',#{name},'%'))
</select>

(4)使用 xml 标签(没有试过)

<select id="searchName" resultType="map" parameterType="amp">
<bind name="pattern1" value="'%' + _parameter.name + '%'" />
SELECT * FROM test_student where username LIKE CONCAT(CONCAT('%',#{name},'%'))
</select>

更多文章链接

猜你喜欢

转载自blog.csdn.net/qq_40147863/article/details/88074591