编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

springBoot中使用mybatisflex拦截器添加数据库表名前缀

wxchong 2024-07-29 08:04:27 开源技术 13 ℃ 0 评论

#精品长文创作季#

在某些情况下,生产环境中的数据库表名可能会在表名前面添加一个特定的前缀,以区分不同的数据库或者模块。这种情况下,开发环境中的表名与生产环境中的表名不一致,并且生产环境中的表名会包含额外的前缀。

例如,在开发环境中,一个表可能被命名为"user",而在生产环境中,该表可能被命名为"prod_user",其中"prod_"是一个前缀用来表示这是生产环境中的表。这样的设计可以帮助区分不同环境下的表,避免混淆和冲突。

在这种情况下,开发人员在编写SQL查询语句时需要注意表名的差异,确保在不同环境中都能正确地访问和操作数据库表。同时,也需要在开发过程中考虑到生产环境中的表名前缀,以确保代码在部署到生产环境后能够正常运行。

1.引入相关的依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>log4j-to-slf4j</artifactId>
                <groupId>org.apache.logging.log4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <artifactId>asm</artifactId>
                <groupId>org.ow2.asm</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.mybatis-flex</groupId>
        <artifactId>mybatis-flex-spring-boot-starter</artifactId>
        <version>${mybatis-flex.version}</version>
    </dependency>
    <dependency>
        <groupId>com.mybatis-flex</groupId>
        <artifactId>mybatis-flex-processor</artifactId>
        <version>${mybatis-flex.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <alibaba.version>1.2.6</alibaba.version>
    <mybatis-flex.version>1.7.2</mybatis-flex.version>
</properties>

2.基于使用MyBatisFlex内置的方法查询数据自动对数据库的表名添加一个前缀

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.table.TableManager;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;
import java.util.Set;

/**
 * 因为生产环境中的数据库与本地环境的表名不一致的问题
 */
@Configuration
public class MyBatisFlexConfiguration implements MyBatisFlexCustomizer {

    @Value("${spring.profiles.active}")
    private String active;

    //动态配置为数据库的表添加一个前缀
    Set<String> tableSet=new HashSet<>();
    {
        tableSet.add("user_info");
    }

    @Override
    public void customize(FlexGlobalConfig globalConfig) {
        //我们可以在这里进行一些列的初始化配置,实现对mybatisFlex调用方法的sql进行拦截,mapper.xml中的sql不会进行拦截
        TableManager.setDynamicTableProcessor(tableName -> {
            if("pro".equals(active) && tableSet.contains(tableName.toLowerCase())){
                return "test_"+tableName.toLowerCase();
            }else{
                return tableName;
            }
        });
    }

}

3.针对比较复杂的xml的sql查询,为了使开发环境与测试环境不用修改代码,采用拦截xml的sql,将其中sql的表名添加一个前缀,使其sql中开发环境与生产环境不用修改表名

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 因为生产环境中的表与测试环境的不一样
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class UpdateTableName implements Interceptor {

    @Value("${spring.profiles.active}")
    private String profilesActive;

    private Map<String, String> map = new HashMap<>();

    {
        final String prefix = "test_";
        String[] tables = {"user_info"};
        for (String table : tables) {
            map.put(table, (prefix + table).toLowerCase());
        }
    }

    /**
     * 根据环境修改相应的表名
     * @param sql 传入初始的sql语句
     * @return 返回修改为的sql
     */
    private String changeTable(String sql) {
        //为生产环境的sql的相应的表名,添加一个test_的前缀
        if (!"dev".equals(profilesActive)) {
            String[] sqlArr = sql.replaceAll("\\s+", " ").split(" ");
            StringBuilder sbd = new StringBuilder();
            for (String str : sqlArr) {
                if (map.containsKey(str.toUpperCase())) sbd.append(map.get(str));
                else sbd.append(str);
                sbd.append(" ");
            }
            return sbd.toString();
        }
        return sql;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        if(getDataUpdate(ms)==null){
            return invocation.proceed();
        }
        String sql = ms.getBoundSql(args[1]).getSql();
        //将小写转化为大写
        String upperCaseSQL = changeTable(sql);
        BoundSql boundSql = ms.getBoundSql(args[1]);
        // 重新塞回去
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), upperCaseSQL, boundSql.getParameterMappings(), boundSql.getParameterObject());
        MappedStatement newMs = newMappedStatement(ms, newBoundSql);
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        args[0] = newMs;
        return invocation.proceed();
    }

    /**
     * 针对个别的sql,需要将sql的表名转化为小写
     */
    private DataUpdate getDataUpdate(MappedStatement mappedStatement) throws ClassNotFoundException {
        DataUpdate dataUpdate=null;
        String id=mappedStatement.getId();
        String className= id.substring(0,id.lastIndexOf("."));
        String methodName=id.substring(id.lastIndexOf(".")+1);
        final Class<?> cls=Class.forName(className);
        final Method[] methods=cls.getMethods();
        for(Method method:methods){
            if(method.getName().equals(methodName) && method.isAnnotationPresent(DataUpdate.class)){
                dataUpdate=method.getAnnotation(DataUpdate.class);
                break;
            }
        }
        return dataUpdate;
    }

    private MappedStatement newMappedStatement(MappedStatement ms, BoundSql newBoundSql) {
        MappedStatement.Builder builder = new
                MappedStatement.Builder(ms.getConfiguration(), ms.getId(), new BoundSqlSource(newBoundSql), ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    class BoundSqlSource implements SqlSource {
        private BoundSql boundSql;
        public BoundSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}

这样的话,我们通过控制台打印相关的sql语句,可以看到相关的sql语句已进行自动添加上对应的test_前缀

select * from test_login_info

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表