MyBatis Dynamic Table Names: Complete Guide
One way to achieve dynamic table names in MyBatis is by using the functionality of MyBatis dynamic SQL.
- To begin with, define a parameter for a dynamic table name in the MyBatis Mapper file, for example:
<select id="selectById" parameterType="java.lang.Long" resultType="com.example.User">
SELECT * FROM ${tableName} WHERE id = #{id}
</select>
- In Java code, pass a dynamic table name parameter by calling the MyBatis interface method.
public User getUserById(Long id, String tableName) {
Map<String, Object> params = new HashMap<>();
params.put("id", id);
params.put("tableName", tableName);
return userMapper.selectById(params);
}
By using the above method, the functionality of dynamically passing in table names in MyBatis can be achieved. It is important to be cautious when dynamically passing in table names to prevent SQL injection attacks. Security can be ensured by validating or filtering the tableName.