您的位置:宽带测速网 > 网络知识 > mybatis动态表名怎么防止SQL注入

mybatis动态表名怎么防止SQL注入

2025-06-19 16:11来源:互联网 [ ]

要防止 MyBatis 中的 SQL 注入,可以通过以下方式来动态构建表名:

    在 Mapper 接口中使用 @Param 注解传递表名参数,并在 SQL 语句中使用 #{paramName} 来引用参数。例如:
public interface MyMapper {List<MyEntity> selectByTableName(@Param("tableName") String tableName);}
<select id="selectByTableName" resultType="MyEntity">SELECT * FROM ${tableName}</select>
    使用 MyBatis 提供的动态 SQL 标签,如 等来根据不同的条件构建不同的 SQL 语句。这样可以在构建 SQL 语句时对表名进行校验和处理。例如:
<select id="selectByTableName" resultType="MyEntity"><choose><when test="tableName == 'table1'">SELECT * FROM table1</when><when test="tableName == 'table2'">SELECT * FROM table2</when><otherwise>SELECT * FROM defaultTable</otherwise></choose></select>

这样可以确保表名参数不会被直接拼接到 SQL 语句中,并且对传入的表名进行了校验和处理,从而防止 SQL 注入攻击。