mybatis運行時攔截ParameterHandler注入參數


    在實現多租戶系統時,每個租戶下的用戶,角色,權限,菜單都是獨立的,每張表里都有租戶Id字段 (tenantId),每次做數據庫操作的時候都需要帶上這個字段,很煩。

現在的需求就是在mybatis向sql設置參數時攔截,獲取當前登錄用戶的tenantId,若參數的集合中沒有 tenantId,將當前登錄用戶的tenantId 放到 sql參數的集合中,

這樣就不必在業務代碼中關心租戶信息了。

具體的做法就是攔截ParameterHandler的 setParameters 方法, 將 tenantId 添加到要設置到參數中,如果是 insert 操作 需要 sql 生成錢攔截,將tenantId設置到實體中

代碼如下

 

package com.ipampas.panshi.interceptor;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ClassUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * User : liulu
 * Date : 2017/12/1 11:30
 * version $Id: ParamInterceptor.java, v 0.1 Exp $
 */
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "createCacheKey", args = {MappedStatement.class, Object.class, RowBounds.class, BoundSql.class})
}
)
public class ParamInterceptor implements Interceptor {

    private static final String PARAM_KEY = "tenantId";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        // 攔截 Executor 的 update 方法 生成sql前將 tenantId 設置到實體中
        if (invocation.getTarget() instanceof Executor && invocation.getArgs().length == 2) {
            return invokeUpdate(invocation);
        }
        // 攔截 Executor 的 createCacheKey 方法,pageHelper插件會攔截 query 方法,調用此方法,提前將參數設置到參數集合中
        if (invocation.getTarget() instanceof Executor && invocation.getArgs().length == 4) {
            return invokeCacheKey(invocation);
        }
        //攔截 ParameterHandler 的 setParameters 方法 動態設置參數
        if (invocation.getTarget() instanceof ParameterHandler) {
            return invokeSetParameter(invocation);
        }
        return null;
    }

    private Object invokeCacheKey(Invocation invocation) throws Exception {
        Executor executor = (Executor) invocation.getTarget();
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        if (ms.getSqlCommandType() != SqlCommandType.SELECT) {
            return invocation.proceed();
        }

        Object parameterObject = invocation.getArgs()[1];
        RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];
        BoundSql boundSql = (BoundSql) invocation.getArgs()[3];

        List<String> paramNames = new ArrayList<>();
        boolean hasKey = hasParamKey(paramNames, boundSql.getParameterMappings());

        if (!hasKey) {
            return invocation.proceed();
        }
        // 改寫參數
        parameterObject = processSingle(parameterObject, paramNames);

        return executor.createCacheKey(ms, parameterObject, rowBounds, boundSql);
    }

    private Object invokeUpdate(Invocation invocation) throws Exception {
        Executor executor = (Executor) invocation.getTarget();
        // 獲取第一個參數
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        // 非 insert 語句 不處理
        if (ms.getSqlCommandType() != SqlCommandType.INSERT) {
            return invocation.proceed();
        }
        // mybatis的參數對象
        Object paramObj = invocation.getArgs()[1];
        if (paramObj == null) {
            return invocation.proceed();
        }

        // 插入語句只傳一個基本類型參數, 不做處理
        if (ClassUtils.isPrimitiveOrWrapper(paramObj.getClass())
                || String.class.isAssignableFrom(paramObj.getClass())
                || Number.class.isAssignableFrom(paramObj.getClass())) {
            return invocation.proceed();
        }

        processParam(paramObj);
        return executor.update(ms, paramObj);
    }


    private Object invokeSetParameter(Invocation invocation) throws Exception {

        ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
        PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];

        // 反射獲取 BoundSql 對象,此對象包含生成的sql和sql的參數map映射
        Field boundSqlField = parameterHandler.getClass().getDeclaredField("boundSql");
        boundSqlField.setAccessible(true);
        BoundSql boundSql = (BoundSql) boundSqlField.get(parameterHandler);

        List<String> paramNames = new ArrayList<>();
        // 若參數映射沒有包含的key直接返回
        boolean hasKey = hasParamKey(paramNames, boundSql.getParameterMappings());
        if (!hasKey) {
            return invocation.proceed();
        }

        // 反射獲取 參數對像
        Field parameterField = parameterHandler.getClass().getDeclaredField("parameterObject");
        parameterField.setAccessible(true);
        Object parameterObject = parameterField.get(parameterHandler);

        // 改寫參數
        parameterObject = processSingle(parameterObject, paramNames);

        // 改寫的參數設置到原parameterHandler對象
        parameterField.set(parameterHandler, parameterObject);
        parameterHandler.setParameters(ps);
        return null;
    }

    // 判斷已生成sql參數映射中是否包含tenantId
    private boolean hasParamKey(List<String> paramNames, List<ParameterMapping> parameterMappings) {
        boolean hasKey = false;
        for (ParameterMapping parameterMapping : parameterMappings) {
            if (StringUtils.equals(parameterMapping.getProperty(), PARAM_KEY)) {
                hasKey = true;
            } else {
                paramNames.add(parameterMapping.getProperty());
            }
        }
        return hasKey;
    }

    private Object processSingle(Object paramObj, List<String> paramNames) throws Exception {

        Map<String, Object> paramMap = new MapperMethod.ParamMap<>();
        if (paramObj == null) {
            paramMap.put(PARAM_KEY, 1L);
            paramObj = paramMap;
            // 單參數 將 參數轉為 map
        } else if (ClassUtils.isPrimitiveOrWrapper(paramObj.getClass())
                || String.class.isAssignableFrom(paramObj.getClass())
                || Number.class.isAssignableFrom(paramObj.getClass())) {
            if (paramNames.size() == 1) {
                paramMap.put(paramNames.iterator().next(), paramObj);
                paramMap.put(PARAM_KEY, 1L);
                paramObj = paramMap;
            }
        } else {
            processParam(paramObj);
        }

        return paramObj;
    }

    private void processParam(Object parameterObject) throws IllegalAccessException, InvocationTargetException {
        // 處理參數對象  如果是 map 且map的key 中沒有 tenantId,添加到參數map中
        // 如果參數是bean,反射設置值
        if (parameterObject instanceof Map) {
            ((Map) parameterObject).putIfAbsent(PARAM_KEY, 1L);
        } else {
            PropertyDescriptor ps = BeanUtils.getPropertyDescriptor(parameterObject.getClass(), PARAM_KEY);
            if (ps != null && ps.getReadMethod() != null && ps.getWriteMethod() != null) {
                Object value = ps.getReadMethod().invoke(parameterObject);
                if (value == null) {
                    ps.getWriteMethod().invoke(parameterObject, 1L);
                }
            }
        }
    }

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

    @Override
    public void setProperties(Properties properties) {

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM