What is the method to prevent injection of dynamic table names in MyBatis?
MyBatis offers a method to prevent dynamic table name injection by using dynamic SQL and parameter replacement.
– in the case that - Make a decision.
- at what time
- Alternatively
<select id="selectUserById" resultType="User">
SELECT * FROM
<choose>
<when test="tableType == 'A'">
table_A
</when>
<when test="tableType == 'B'">
table_B
</when>
<otherwise>
table_C
</otherwise>
</choose>
WHERE id = #{id}
</select>
- Use parameter replacement: pass the table name as a parameter to the SQL statement to prevent injection by replacing the parameters. For example:
<select id="selectUserById" resultType="User">
SELECT * FROM #{tableName}
WHERE id = #{id}
</select>
Passing the table name as a parameter to the MyBatis method in Java code.
String tableName = "table_A";
int id = 1;
User user = sqlSession.selectOne("selectUserById", Collections.singletonMap("tableName", tableName));
By using this method, it ensures that table names are obtained from trusted sources, eliminating the risk of injection caused by directly concatenating table names.