Mybatis拦截器实现SAAS平台(动态修改SQL)随笔

首先,自定义拦截器



import com.swzx.risktech.model.User;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

/**
 * author:cs  2019/02/28
 */

//拦截StatementHandler类中参数类型为Statement的 prepare 方法
//即拦截 Statement prepare(Connection var1, Integer var2) 方法
@Component
@Intercepts({@Signature(type = StatementHandler.class,method = "prepare",args = {Connection.class,Integer.class})})
public class SqlInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session=request.getSession();
        //获取到原始sql语句
        String sql = boundSql.getSql();
        String mSql = "";
        String strsql = sql.replace(" ","");
        User user = (User)session.getAttribute("loginUser");
        if(strsql.indexOf("cid=")==-1) {
            if (sql.indexOf("where")!=-1){
                mSql = sql + " and cid="+user.getCid();
            }else{
                mSql = sql + " where and cid="+user.getCid();
            }
        }
        //通过反射修改sql语句
        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql, mSql);
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {
        //此处可以接收到配置文件的property参数
    }
}

然后就没有然后了,就是这么简单。

你可能感兴趣的:(web,java,mysql)