MyBatis:模糊查询的4种实现方式
在mybatis中经常要写到like 查询,今天遇到了问题:在xml文件mapper中应该怎么写呢,刚开始我是这么写的:
<mapper namespace="cn.imyjs.mapper.TimuMapper">
<select id="selectOne" resultType="Timu">
select * from QuestionBank where q_title like %#{title}% LIMIT 1;
</select>
</mapper>
结果报错了:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%'党的十九大'% LIMIT 1' at line 1
通过看报错信息不难发现是SQL语句书写有误导致的,原因是:缺少单引号。
解决方法一
手动的去在查询字符串中添加“%”通配符。
<mapper namespace="cn.imyjs.mapper.TimuMapper">
<select id="selectOne" resultType="Timu">
select * from QuestionBank where q_title like #{title} LIMIT 1;
</select>
</mapper>
# Java:
Timu timu = mapper.selectOne("%党的十九大%");
缺点:有一点不方便的地方:在调用方法传参时需要调用者手动的添加%号通配符,显然是麻烦的。
解决方法二
通过使用“$”也可以实现。
<mapper namespace="cn.imyjs.mapper.TimuMapper">
<select id="selectOne" resultType="Timu">
select * from QuestionBank where q_title like '%${title}%' LIMIT 1;
</select>
</mapper>
缺点:通过$的方式拼接的sql语句,不再是以占位符的形式生成sql,而是以拼接字符串的方式生成sql,这样做带来的问题是:会引发sql注入的问题。
解决方法三
通过前两种写法,虽然可以解决模糊查询的问题,但是还是不好,因为通过%的方式会引发sql注入的问题,现在的期望是:既能够解决sql注入又能在配置文件中写%该如何实现呢,可以借助mysql的函数:concat函数。
<mapper namespace="cn.imyjs.mapper.TimuMapper">
<select id="selectOne" resultType="Timu">
select * from QuestionBank where q_title like concat('%',#{title},'%') LIMIT 1;
</select>
</mapper>
缺点:concat必然会先耗时间去执行函数费数据库的事。
这种方法也可以使用$,不过需要特别留意单引号的问题。
<mapper namespace="cn.imyjs.mapper.TimuMapper">
<select id="selectOne" resultType="Timu">
select * from QuestionBank where q_title like concat('%','${title}','%') LIMIT 1;
</select>
</mapper>
解决方法四
bind标签
<select id="selectOne" resultType="Timu">
<bind name="pattern" value="'%' + title + '%'" />
select *
from QuestionBank
where q_title LIKE #{pattern} LIMIT 1;
</select>
bind标签的两个属性都是不选项,name为绑定到上下文的变量名,value为OGNL表达式。 使用bind拼接字符串不仅可以避免因更换数据库而修改SQL,也能预防SQL注入。
补充
#{ }是预编译处理,MyBatis在处理#{ }时,它会将sql中的#{ }替换为?,然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号,使用占位符的方式提高效率,可以防止sql注入。
${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中,可能引发sql注入。
微信关注
阅读剩余
版权声明:
作者:理想
链接:https://www.imyjs.cn/archives/430
文章版权归作者所有,未经允许请勿转载。
THE END