【基于Mybatis拦截器实现不同用户使用不同的数据表】

基于Mybatis拦截器实现不同用户使用不同的数据表

一、实现思路

将数据表命名格式定为:baseTableName_usertId,sql语句中的表名就直接写为 baseTableName,然后通过定义Mybatis拦截器将baseTableName替换为baseTableName_usertId。

二、定义一个Mybatis拦截器

package com.ruoyi.framework.interceptor;

import com.ruoyi.common.utils.ShiroUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
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.stereotype.Component;

import java.util.*;


/**
 * @description: 动态替换表名拦截器
 * @author: zengxi
 * @created: 2023/03/03
 */

//method = "query"拦截select方法、而method = "update"则能拦截insert、update、delete的方法
@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}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
//@Component
public class ReplaceTableInterceptor implements Interceptor {

    private final static List<String> TABLE_LIST = new ArrayList<String>();

    static {
        //表名长的放前面,避免字符串匹配的时候先匹配替换子集
        TABLE_LIST.add("test");
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 拦截sql
        Object[] args = invocation.getArgs();
        // 获取MappendStatement对象
        MappedStatement ms = (MappedStatement) args[0];
        Object parameteObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameteObject);
        String sql = boundSql.getSql();
        if (isReplaceTableName(sql)){ // 判断是否需要替换表名
            String newSql = replaceTableName(sql);
            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
            MappedStatement newMs = copyMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
            args[0] = newMs;
        }


        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // 创建代理对象
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可选实现,不需要做任何事情
    }

    /***
     * MappedStatement构造器接受的是SqlSource
     * 实现SqlSource接口,将BoundSql封装进去
     */
    public static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }


    /***
     * 复制一个新的MappedStatement
     * @param ms
     * @param newSqlSource
     * @return
     */
    private MappedStatement copyMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, 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(String.join(",", ms.getKeyProperties()));
        }
        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();
    }

    /***
     * 判断是否需要替换表名
     * @param sql
     * @return
     */
    private boolean isReplaceTableName(String sql){
        for(String tableName : TABLE_LIST){
            if(sql.contains(tableName)){
                return true;
            }
        }
        return false;
    }

    /***
     * 将sql中的表名替换
     * @param sql
     * @return
     */
    private String replaceTableName(String sql){
        Long userId = ShiroUtils.getUserId(); // 获取用户id
        if (userId != null){
            for(String tableName : TABLE_LIST){
                String newTableName = tableName + "_" + userId;
                sql = sql.replace(tableName,newTableName);
            }
        }
        return sql;
    }

}

三、注入Mybatis拦截器

	@Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // 将自定义的拦截器加入到拦截器列表中
        sessionFactory.setPlugins(new Interceptor[] {new ReplaceTableInterceptor()});
        return sessionFactory;
    }

注意如果在项目中使用了PageHelper分页插件,会导致query时,拦截器失效,但是insert、update、delete操作时不会失效,解决方法如下
可以在mybatis-config.xml文件中配置拦截器执行顺序

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor" />
        <plugin interceptor="com.ruoyi.framework.interceptor.ReplaceTableInterceptor" />
    </plugins>

参考文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus是一个基于MyBatis的增强工具,提供了许多便捷的功能,其中包括数据拦截器(Data Interceptor)。 数据拦截器MyBatis-Plus提供的一个特性,用于在SQL语句执行前后对数据进行拦截和处理。通过数据拦截器,可以在执行SQL之前对参数进行修改,或者在执行SQL之后对结果进行处理。 使用数据拦截器可以实现一些常见的需求,比如对敏感字段进行加密解密、对某些特定条件进行数据过滤等。 要使用数据拦截器,首先需要创建一个实现了`com.baomidou.mybatisplus.core.plugins.Interceptor`接口的拦截器类。然后,在MyBatis的配置文件中配置该拦截器: ```xml <configuration> <plugins> <plugin interceptor="com.example.MyInterceptor"/> </plugins> </configuration> ``` 其中`com.example.MyInterceptor`是你自定义的拦截器类的全限定名。 在自定义的拦截器类中,你可以通过重写`intercept`方法来实现对SQL执行前后的处理逻辑。`intercept`方法接收一个`Invocation`对象作为参数,通过该对象可以获取到SQL语句、参数等相关信息。 ```java public class MyInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 在SQL执行前的处理逻辑 // ... // 执行SQL Object result = invocation.proceed(); // 在SQL执行后的处理逻辑 // ... return result; } } ``` 需要注意的是,如果你使用的是Spring Boot,可以通过`@Bean`注解将拦截器类注入到Spring容器中。如果是非Spring Boot项目,则需要在MyBatis的配置文件中显式配置拦截器。 以上就是使用MyBatis-Plus数据拦截器的基本介绍,希望对你有所帮助。如有更多问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值