没有合适的资源?快使用搜索试试~ 我知道了~
MyBatis实现模糊查询的几种方式
1 下载量 38 浏览量
2020-08-27
01:17:51
上传
评论
收藏 220KB PDF 举报
温馨提示
试读
3页
主要介绍了MyBatis实现模糊查询的几种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
资源推荐
资源详情
资源评论
MyBatis实现模糊查询的几种方式实现模糊查询的几种方式
主要介绍了MyBatis实现模糊查询的几种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
在学习MyBatis过程中想实现模糊查询,可惜失败了。后来上百度上查了一下,算是解决了。记录一下MyBatis实现模糊查询的几种方式。
数据库表名为test_student,初始化了几条记录,如图:
起初我在MyBatis的mapper文件中是这样写的:
<select id="searchStudents" resultType="com.example.entity.StudentEntity"
parameterType="com.example.entity.StudentEntity">
SELECT * FROM test_student
<where>
<if test="age != null and age != '' and compare != null and compare != ''">
age
${compare}
#{age}
</if>
<if test="name != null and name != ''">
AND name LIKE '%#{name}%'
</if>
<if test="address != null and address != ''">
AND address LIKE '%#{address}%'
</if>
</where>
ORDER BY id
</select>
写完后自我感觉良好,很开心的就去跑程序了,结果当然是报错了:
经百度得知,这么写经MyBatis转换后(‘%#{name}%')会变为(‘%?%'),而(‘%?%')会被看作是一个字符串,所以Java代码在执行找不到用于匹配参数的 ‘?' ,然后就报错了。
解决方法解决方法
1.用用${…}代替代替#{…}
<select id="searchStudents" resultType="com.example.entity.StudentEntity"
parameterType="com.example.entity.StudentEntity">
SELECT * FROM test_student
<where>
<if test="age != null and age != '' and compare != null and compare != ''">
age
${compare}
#{age}
</if>
<if test="name != null and name != ''">
AND name LIKE '%${name}%'
</if>
<if test="address != null and address != ''">
AND address LIKE '%${address}%'
</if>
</where>
ORDER BY id
</select>
查询结果如下图:
注:使用
${…}
不能有效防止
SQL
注入,所以这种方式虽然简单但是不推荐使用!!!
2.把把'%#{name}%'改为改为”%”#{name}”%”
<select id="searchStudents" resultType="com.example.entity.StudentEntity"
parameterType="com.example.entity.StudentEntity">
SELECT * FROM test_student
<where>
<if test="age != null and age != '' and compare != null and compare != ''">
age
${compare}
#{age}
</if>
<if test="name != null and name != ''">
AND name LIKE "%"#{name}"%"
</if>
<if test="address != null and address != ''">
AND address LIKE "%"#{address}"%"
</if>
</where>
ORDER BY id
</select>
查询结果:
资源评论
weixin_38626928
- 粉丝: 2
- 资源: 949
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功