java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > mybatis 拦截器添加参数

mybatis 拦截器添加参数的实现

作者:点滴1993

本文主要介绍了MyBatis拦截器中添加参数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

以登录用户ID为例, 再拦截器中加入,在mapper.xml文件中通过 #{currentUserId}或${currentUserId} 获取参数。

1. 拦截器示例代码

package com.xxx.framework.interceptor;

import com.xxx.common.core.domain.BaseEntity;
import com.xxx.framework.shiro.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * 全局参数拦截器
 *
 * @author xm.z
 */
@Slf4j
@Intercepts({
        @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})}
)
public class GlobalParametersInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object params = args[1];
        if (params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.setCurrentUserId(getCurrentUserId());
        } else if (params instanceof MapperMethod.ParamMap) {
            MapperMethod.ParamMap<Object> map = (MapperMethod.ParamMap) params;
            map.put("currentUserId", getCurrentUserId());
        }
        invocation.getArgs()[1] = params;
        return invocation.proceed();
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 用户ID
     */
    private String getCurrentUserId() {
        try {
            return ShiroUtils.getUserId().toString();
        } catch (Exception ignored) {
            return null;
        }
    }
}

2. 拦截器配置

注:若项目中引用了 PageHelper 分页器,此方法会失效。

package com.xxx.framework.config;

import com.xxx.framework.interceptor.GlobalParametersInterceptor;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 拦截器配置
 *
 * @author xm.z
 */
@Configuration
@ConditionalOnBean({SqlSessionFactory.class})
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MybatisInterceptorConfig {

    private final List<SqlSessionFactory> sqlSessionFactories;

    @PostConstruct
    public void addPageInterceptor() {
        GlobalParametersInterceptor globalParametersInterceptor = new GlobalParametersInterceptor();
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
            sqlSessionFactory.getConfiguration().addInterceptor(globalParametersInterceptor);
        }
    }

}

3. PageHelper拦截器配置

Mybatis 拦截器是采用的责任链模式,一般拦截器中intercept方法中最后执行 invocation.proceed() 方法,PageInterceptor 分页器并未向后传递参数而是执行了query方法, 所以需要将自定义拦截器放在PageInterceptor的后面(PS: 最后加入的拦截器最先执行)。

package com.xxx.framework.config;

import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import com.xxx.framework.interceptor.GlobalParametersInterceptor;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 拦截器配置
 *
 * @author xm.z
 */
@Configuration
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MybatisInterceptorConfig implements BeanPostProcessor {

    private final List<SqlSessionFactory> sqlSessionFactories;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof PageHelperAutoConfiguration) {
            GlobalParametersInterceptor globalParametersInterceptor = new GlobalParametersInterceptor();
            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
                sqlSessionFactory.getConfiguration().addInterceptor(globalParametersInterceptor);
            }
        }
        return bean;
    }
}

到此这篇关于mybatis 拦截器添加参数的实现的文章就介绍到这了,更多相关mybatis 拦截器添加参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文