本文共 2196 字,大约阅读时间需要 7 分钟。
MyBatis-Plus 的 apply
方法允许在查询条件中直接拼接自定义的 SQL 片段。例如:
QueryWrapper queryWrapper = new QueryWrapper<>();queryWrapper.apply("date_format(create_time, '%Y-%m-%d') = {0}", "2023-10-01");
这里,{0}
是占位符,MyBatis-Plus 会自动将其替换为参数值,确保 SQL 安全。
直接将用户输入拼接到 SQL 片段中可能导致严重的 SQL 注入风险。例如:
String userInput = "2023-10-01'; DROP TABLE user; --";queryWrapper.apply("date_format(create_time, '%Y-%m-%d') = '" + userInput + "'");
生成的 SQL 可能变成:
date_format(create_time, '%Y-%m-%d') = '2023-10-01'; DROP TABLE user; --
这会导致 SQL 注入问题。
MyBatis-Plus 的 apply
方法支持占位符(如 {0}
、{1}
),并会对参数进行转义,防止 SQL 注入。例如:
String safeDate = "2023-10-01";queryWrapper.apply("date_format(create_time, '%Y-%m-%d') = {0}", safeDate);
生成的 SQL 是安全的:
date_format(create_time, '%Y-%m-%d') = '2023-10-01'
SqlInjectionUtils
检查输入MyBatis-Plus 提供 SqlInjectionUtils
工具类,可以用于检测输入是否包含 SQL 注入风险。例如:
import com.baomidou.mybatisplus.core.toolkit.sql.SqlInjectionUtils;String userInput = "2023-10-01'; DROP TABLE user; --";if (SqlInjectionUtils.check(userInput)) { throw new IllegalArgumentException("输入包含非法字符");}queryWrapper.apply("date_format(create_time, '%Y-%m-%d') = {0}", userInput);
尽量使用 MyBatis-Plus 提供的安全方法,如 eq
、like
等,而不是直接拼接 SQL。例如:
queryWrapper.eq("date_format(create_time, '%Y-%m-%d')", "2023-10-01");
始终使用占位符
{0}
、{1}
等占位符,而不是直接拼接字符串。验证用户输入
使用安全的 API
eq
、like
等),而不是直接拼接 SQL。定期检查代码
apply
方法示例QueryWrapper queryWrapper = new QueryWrapper<>();String safeDate = "2023-10-01";queryWrapper.apply("date_format(create_time, '%Y-%m-%d') = {0}", safeDate);ListuserList = userMapper.selectList(queryWrapper);
apply
方法示例(不推荐)QueryWrapper queryWrapper = new QueryWrapper<>();String unsafeDate = "2023-10-01'; DROP TABLE user; --";queryWrapper.apply("date_format(create_time, '%Y-%m-%d') = '" + unsafeDate + "'");ListuserList = userMapper.selectList(queryWrapper);
apply
方法可以安全使用,但必须通过占位符和参数化查询来避免 SQL 注入。SqlInjectionUtils
)来检查输入的安全性。转载地址:http://ffffk.baihongyu.com/