在MyBatis中動態(tài)表名的實現(xiàn)可以通過使用MyBatis動態(tài)SQL的功能來實現(xiàn)。以下是一種實現(xiàn)方式:
<select id="selectById" parameterType="java.lang.Long" resultType="com.example.User">
SELECT * FROM ${tableName} WHERE id = #{id}
</select>
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);
}
通過以上方式就可以實現(xiàn)在MyBatis中動態(tài)傳入表名的功能。需要注意的是在動態(tài)傳入表名時要注意防止SQL注入攻擊,可以通過對tableName進行一些校驗或者過濾來保證安全。