mybatis 拦截器添加参数的实现

 更新时间:2024年12月12日 10:27:42   作者:点滴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 拦截器添加参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 启动Solr提示Java版本低问题解决方案

    启动Solr提示Java版本低问题解决方案

    这篇文章主要介绍了启动Solr提示Java版本低问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • Java实现List分组的常见方法详解

    Java实现List分组的常见方法详解

    这篇文章主要为大家详细介绍了使用Java实现List分组的几个常见方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-12-12
  • java实现微信小程序登录态维护的示例代码

    java实现微信小程序登录态维护的示例代码

    本篇文章主要介绍了java实现微信小程序登录态维护的示例代码,具有一定的参考价值,有兴趣的可以了解一下
    2017-09-09
  • spring boot整合flyway实现数据的动态维护的示例代码

    spring boot整合flyway实现数据的动态维护的示例代码

    本文主要介绍了spring boot整合flyway实现数据的动态维护的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-04-04
  • java中forward转发的使用

    java中forward转发的使用

    在Java中,forward转发是一种非常常见且重要的操作,我们将深入探讨forward的概念和用法,并给出一些代码示例来帮助读者更好地理解,感兴趣的可以了解下
    2023-11-11
  • 深入了解Spring中最常用的11个扩展点

    深入了解Spring中最常用的11个扩展点

    我们一说到spring,可能第一个想到的是 IOC(控制反转) 和 AOP(面向切面编程)。除此之外,我们在使用spring的过程中,有没有发现它的扩展能力非常强。今天就来跟大家一起聊聊,在Spring中最常用的11个扩展点
    2022-09-09
  • Java中实现定时任务的两种方法举例详解

    Java中实现定时任务的两种方法举例详解

    这篇文章主要给大家介绍了关于Java中实现定时任务的两种方法,文中总结了各种实现方式的优缺点,并给出了推荐的使用场景,通过代码介绍的非常详细,需要的朋友可以参考下
    2024-12-12
  • Spring Cloud Alibaba教程之Sentinel的使用

    Spring Cloud Alibaba教程之Sentinel的使用

    这篇文章主要介绍了Spring Cloud Alibaba教程之Sentinel的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Windows编写jar启动脚本和关闭脚本的操作方法

    Windows编写jar启动脚本和关闭脚本的操作方法

    脚本文件,通常放入/bin目录下,编写启动脚本需要保证能够识别到对应的jar文件,其次需要保证能够识别到/config中的配置文件信息,这篇文章主要介绍了Windows编写jar启动脚本和关闭脚本的操作方法,需要的朋友可以参考下
    2022-12-12
  • Java实现多线程断点下载

    Java实现多线程断点下载

    这篇文章主要为大家详细介绍了Java实现多线程断点下载的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03

最新评论