1.基于mybatis官方文档
@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {Map<String, Object> paramMap = RequestDataHelper.getRequestData();paramMap.forEach((k, v) -> System.err.println(k + "----" + v));String year = "_2018";int random = new Random().nextInt(10);if (random % 2 == 1) {year = "_2019";}return tableName + year;});interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);return interceptor;}
}
public class RequestDataHelper {private static final ThreadLocal<Map<String, Object>> REQUEST_DATA = new ThreadLocal<>();public static void setRequestData(Map<String, Object> requestData) {REQUEST_DATA.set(requestData);}public static <T> T getRequestData(String param) {Map<String, Object> dataMap = getRequestData();if (CollectionUtils.isNotEmpty(dataMap)) {return (T) dataMap.get(param);}return null;}public static Map<String, Object> getRequestData() {return REQUEST_DATA.get();}
}
2. 使用参数的方式
@Mapper
public interface LogMapper extends BaseMapper<LogEntity> {List<LogEntity> queryAll(@Param("tableName")String tableName);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhubayi.dynatable.mapper.LogMapper"><select id="queryAll" resultType="com.zhubayi.dynatable.entity.LogEntity">select * from ${tableName};</select>
</mapper>