mybtis plus 3.2.0 动态表名sql解析器的配置
一.Configuration
@Configuration public class MybatisPlusConfiguration { public static ThreadLocal<String> inputTableName = new ThreadLocal<>(); @Bean public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); List<ISqlParser> sqlParserList = new ArrayList<>(); DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser(); HashMap<String, ITableNameHandler> map = new HashMap<>(); map.put("user", (metaObject, sql, tableName) -> inputTableName.get()); dynamicTableNameParser.setTableNameHandlerMap(map); sqlParserList.add(dynamicTableNameParser); paginationInterceptor.setSqlParserList(sqlParserList); paginationInterceptor.setSqlParserFilter(metaObject -> { MappedStatement statement = SqlParserHelper.getMappedStatement(metaObject);
//如果是selectById方法,则表名不会被替换,其他的会被动态替换表名 return "com.mp.dao.UserMapper.selectById".equals(statement.getId()); }); return paginationInterceptor; } }
二.测试
传入参数
@Test public void testTableNAme(){ MybatisPlusConfiguration.inputTableName.set("user_2020"); userMapper.selectList(null); }
三.运行结果
可以观察到查询的表名已经被替换