要防止 MyBatis 中的 SQL 注入,可以通过以下方式来动态构建表名:
public interface MyMapper { List<MyEntity> selectByTableName(@Param("tableName") String tableName); } <select id="selectByTableName" resultType="MyEntity"> SELECT * FROM ${tableName} </select> <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 注入攻击。