mybatis項目實現(xiàn)動態(tài)表名的三種方法
實現(xiàn)動態(tài)表名是個很常見的需求,網(wǎng)上也有很多解決方法,這邊總結(jié)了三種實現(xiàn)方式。
一、手動給每個方法加個表名的變量
缺點很明顯,侵入性大,不方便,不推薦
二、mybatis插件機制攔截sql替換表名實現(xiàn)動態(tài)表名
import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.lang.reflect.Proxy; import java.sql.Connection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; /** * mybatis插件實現(xiàn)動態(tài)表名,可以攔截器新增、編輯、刪除、查詢等 */ @Component @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class})}) public class ReplaceTablePlugin implements Interceptor { private static final Logger LOG = LoggerFactory.getLogger(ReplaceTablePlugin.class); private final static Map<String, String> TABLE_MAP = new LinkedHashMap<>(); /** * 需要替換的表(替換前的表名和替換后的表名) */ static { TABLE_MAP.put("t_user", "t_user_20220101"); TABLE_MAP.put("t_org", "t_org_20220202"); } @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = realTarget(invocation.getTarget()); MetaObject metaObject = SystemMetaObject.forObject(statementHandler); doTable(statementHandler, metaObject); return invocation.proceed(); } private void doTable(StatementHandler handler, MetaObject metaStatementHandler) throws ClassNotFoundException { BoundSql boundSql = handler.getBoundSql(); String originalSql = boundSql.getSql(); if (originalSql != null && !originalSql.equals("")) { LOG.info("攔截前的sql:{}", originalSql); if (isReplaceTableName(originalSql)) { for (Map.Entry<String, String> entry : TABLE_MAP.entrySet()) { originalSql = originalSql.replace(entry.getKey(), entry.getValue()); } LOG.info("攔截后的sql:{}", originalSql); metaStatementHandler.setValue("delegate.boundSql.sql", originalSql); } } } private boolean isReplaceTableName(String sql) { for (String tableName : TABLE_MAP.keySet()) { if (sql.contains(tableName)) { return true; } } return false; } @Override public Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } return target; } @Override public void setProperties(Properties properties) { } /** * Obtain real processing objects, possibly multi-layer agents * * @param target * @param <T> * @return */ public static <T> T realTarget(Object target) { if (Proxy.isProxyClass(target.getClass())) { MetaObject metaObject = SystemMetaObject.forObject(target); return realTarget(metaObject.getValue("h.target")); } return (T) target; } }
三、mybatis-plus的DynamicTableNameInnerInterceptor實現(xiàn)
3.1引入mybatis-plus的pom jar包依賴
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-extension</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-annotation</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-core</artifactId> <version>3.5.2</version> </dependency>
3.2 實現(xiàn)的配置類
import java.util.Map; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.redis.core.RedisTemplate; /** * * mybatis-plus實現(xiàn)動態(tài)替換表名 */ @MapperScan("com.xiaweiyi8080.dal.mapper") @ComponentScan({"com.xiaweiyi8080.dal.manager"}) @Slf4j public class MyBatisPlusConfiguration { @Autowired private RedisTemplate redisTemplate; // 配置文件里配置的哪些表需要動態(tài)表名 @Value("${xxxxx.tableName:}") private String dynamicTableName; @Bean public MybatisPlusInterceptor dynamicTableNameInterceptor() { log.info("------拿到的dynamicTableName={}", dynamicTableName); MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor(); dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> { // 獲取參數(shù)方法 Map<String, Object> paramMap = RequestDataHelper.getRequestData(); if (CollectionUtil.isNotEmpty(paramMap)) { paramMap.forEach((k, v) -> log.info(k + "----" + v)); } if (StringUtils.isNotBlank(dynamicTableName) && dynamicTableName.contains(tableName)) { log.info("------替換前表名={}", tableName); String suffix = "_20220101"; tableName += suffix; log.info("------替換后表名={}", tableName); } return tableName; }); interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor); return interceptor; } }
到此這篇關(guān)于mybatis項目實現(xiàn)動態(tài)表名的三種方法的文章就介紹到這了,更多相關(guān)mybatis 動態(tài)表名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot實現(xiàn)Java阿里短信發(fā)送代碼實例
這篇文章主要介紹了springboot實現(xiàn)Java阿里短信發(fā)送代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02SpringBoot攔截器實現(xiàn)項目防止接口重復(fù)提交
基于SpringBoot框架來開發(fā)業(yè)務(wù)后臺項目時,接口重復(fù)提交是一個常見的問題,本文主要介紹了SpringBoot攔截器實現(xiàn)項目防止接口重復(fù)提交,具有一定的參考價值,感興趣的可以了解一下2023-09-09mybatis mybatis-plus-generator+clickhouse自動生成代碼案例詳解
這篇文章主要介紹了mybatis mybatis-plus-generator+clickhouse自動生成代碼案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08快速搭建Spring Boot+MyBatis的項目IDEA(附源碼下載)
這篇文章主要介紹了快速搭建Spring Boot+MyBatis的項目IDEA(附源碼下載),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12