官网文档
https://baomidou.com/plugins/dynamic-table-name/
Java代码
配置拦截器
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* MyBatis Plus 配置
* 动态表名插件
*/
@Configuration
public class MyBatisPlusConfig {
public static ThreadLocal<String> tableNameHolder = new ThreadLocal<>();
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加动态表名插件
DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
// 从 ThreadLocal 中获取动态表名
String dynamicTableName = tableNameHolder.get();
if (dynamicTableName != null) {
return dynamicTableName; // 返回动态表名
}
return tableName; // 默认表名
});
interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
return interceptor;
}
/**
* 生成动态表名
* @param originalTableName 原表名
* @param cityid 城市
* @return 动态表名
*/
public static String generateDynamicTableName(String originalTableName, String cityid) {
// 获取当前年份
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
String year = sdf.format(new Date());
// 生成动态表名
return originalTableName + "_" + cityid + "_" + year;
}
}
使用动态表名
import com.baoer.terminaltcpserver.config.MyBatisPlusConfig;
public class SomeService {
public void someMethod() {
// 假设原表名为 "feedbacklog"
String originalTableName = "feedbacklog";
String cityid = "1";
// 1.生成动态表名
String dynamicTableName = MyBatisPlusConfig.generateDynamicTableName(originalTableName, cityid);
// 2.设置到 ThreadLocal 中
MyBatisPlusConfig.tableNameHolder.set(dynamicTableName);
try {
// 执行数据库操作
// 例如:userMapper.selectList(null);
} finally {
// 3.清除 ThreadLocal 中的值
MyBatisPlusConfig.tableNameHolder.remove();
}
}
}
标签:MybatisPlus,String,表名,import,动态,public,MyBatisPlusConfig
From: https://www.cnblogs.com/aeolian/p/18552868