在 MyBatis ,您可以像这样标记参数应插入到 SQL 中的位置:
SELECT * FROM Person WHERE id = #{id}
此语法会激活正确的转义等,以避免 SQL 注入(inject)攻击等。如果您有可信输入并且想要跳过转义,您可以逐字插入参数:
SELECT * FROM {tableName} WHERE id = #{id}
现在,我想对不安全的输入进行 LIKE 搜索,所以我想做的是:
SELECT * FROM Person WHERE name LIKE #{beginningOfName} || '%'
不幸的是,但是,重要的数据库服务器 don't support the ||
syntax for concatenation :
MSSQL - Breaks the standard by using the '+' operator instead of '||'.
...
MySQL - Badly breaks the standard by redefining || to mean OR.
所以,我可以做任何一个
SELECT * FROM Person WHERE name LIKE CONCAT(#{beginningOfName}, '%')
在本例中,仅限于 MySQL,或者我可以做
SELECT * FROM Person WHERE name LIKE '{beginningOfName}%'
并且必须自己清理输入。
有更优雅的解决方案吗?
最佳答案
您可以使用绑定(bind)语法
The bind element lets you create a variable out of an OGNL expression and bind it to the context. For example:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
关于sql - (如何)我可以在 MyBatis 的 SQL 查询中安全且与数据库无关地使用 "LIKE"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7491291/