mybatis-plus如何使用动态表名呢?
下文笔者讲述mybatis-plus动态表名的使用简介说明,如下所示
mybatis-plus中使用动态表名的实现思路
方式1:动态拼接
然后使用$方法注入表名
方式2:
使用 mybatis-plus提供的动态表名插件
例:mybatis-plus动态表名
原始方法一
根据时间获取动态拼接成数据库表名
String tableName = "数据库表名" + date;
使用$的办法注入到SQL语句中
SELECT * FROM ${tableName}
方法二:
使用mybatis-plus提供的动态表名插件
MyBatis-Plus-动态表名插件地址
引入依赖
<dependency>
<groupid>com.baomidou</groupid>
<artifactid>mybatis-plus-boot-starter</artifactid>
<version>3.4.1.tmp</version>
</dependency>
定义
public enum DynamicTableTreadLocal {
INSTANCE;
private ThreadLocal<String> tableName = new ThreadLocal<>();
public String getTableName() {
return tableName.get();
}
public void setTableName(String tableName) {
this.tableName.set(tableName);
}
public void remove() {
tableName.remove();
}
}
在MybatisPlusConfig中
配置自己的动态表规则
private static final String DYNAMIC_TABLE_PRE = "原始数据库表名";
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
dynamicTableNameParser.setTableNameHandlerMap(new HashMap<String, ITableNameHandler>(2) {{
//动态表规则-生成自己需要的动态表名
put(DYNAMIC_TABLE_PRE, (metaObject, sql, tableName) -> DynamicTableTreadLocal.INSTANCE.getTableName());
}});
paginationInterceptor.setSqlParserlist(Collections.singletonList(dynamicTableNameParser));
最后我们在我们的实现类中调用次方法
//获取当前表格
String tableName = this.tableName();
List<T> list ;
try {
DynamicTableTreadLocal.INSTANCE.setTableName(tableName);
list = TDao.getPage(params);
}
mybatis-plus实现动态表名的功能
DynamicTableTreadLocal
主动remove
在使用ThreadLocalMap使用ThreadLocal的弱引用作为key
且ThreadLocal得外部不存在强引用
key(ThreadLocal)就会被GC回收
这样就会造成ThreadLocalMap中key为null
并且value此时存在强引用
线程退出时value的强引用才会断开
当前线程未结束时,key为null的value就会存在强引用链
就导致了内存泄漏。
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
此处需要手动删除key,不然就会导致内存泄漏。
finally {
DynamicTableTreadLocal.INSTANCE.remove();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


