mybatis动态表名怎么防止SQL注入
要防止 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 标签,如
<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 注入攻击。