SpringBoot使用自定义Mybatis拦截器

开发过程中经常回需要对要执行的sql加以自定义处理,比如分页,计数等。通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。

分页小引用https://blog.csdn.net/A__yes/article/details/101424728

@Intercepts({@Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class, RowBounds.class,ResultHandler.class})})
public class MyPageInterceptor implements Interceptor {
    private static final Logger logger= LoggerFactory.getLogger(MyPageInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        logger.warn(invocation.toString());
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o,this);
    }
    @Override
    public void setProperties(Properties properties) {
        logger.warn(properties.toString());
    }
}

我的配置

mybatis:
  type-aliases-package: me.zingon.pagehelper.model
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
    default-fetch-size: 100
    default-statement-timeout: 30

在springboot中要给mybatis加上这个拦截器,有三种方法,前两种方法在启动项目时不会自动调用自定义拦截器的setProperties方法。

第一种

直接给自定义拦截器添加一个 @Component注解,当调用sql时结果如下,可以看到拦截器生效了,但是启动时候并没有自动调用setProperties方法。

第二种

在配置类里添加拦截器,这种方法结果同上,也不会自动调用setProperties方法。


@Configuration
public class MybatisConfig {
    @Bean
    ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.addInterceptor(new MyPageInterceptor());
            }
        };
    }
}
第三种

这种方法就是跟以前的配置方法类似,在yml配置文件中指定mybatis的xml配置文件,注意config-location属性和configuration属性不能同时指定

mybatis:
  config-location: classpath:mybatis.xml
  type-aliases-package: me.zingon.pagehelper.model
  mapper-locations: classpath:mapper/*.xml

mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="me.zingon.pacargle.model"/>
    </typeAliases>
    <plugins>
        <plugin interceptor="me.zingon.pagehelper.interceptor.MyPageInterceptor"> 
            <property name="dialect" value="oracle"/>
        </plugin>
    </plugins>
</configuration>

可以看到,在启动项目的时候setProperties被自动调用了
在这里插入图片描述

总结

前两种方法可以在初始化自定义拦截器的时候通过 @Value 注解直接初始化需要的参数。

Spring Boot 和 MyBatis 结合使用时,自定义拦截器是一种强大的工具,允许开发者在执行 SQL 之前、之后或在特定业务逻辑点进行额外的操作。以下是如何使用自定义拦截器的一般步骤: 1. **创建拦截器接口**: 首先,你需要定义一个实现了 `org.apache.ibatis.interceptor.Interceptor` 接口的类,这个类通常是抽象的,包含你想要执行的业务逻辑方法。 ```java public interface CustomInterceptor extends Interceptor { // 自定义方法,例如预处理SQL前、后操作 Object before(Invocation invocation); // 其他可能的方法,如执行SQL后处理 Object after(Invocation invocation) throws Throwable; } ``` 2. **实现具体拦截器类**: 在具体类中,你需要重写上述接口的方法,并添加你需要的业务逻辑。 ```java public class YourCustomInterceptor implements CustomInterceptor { @Override public Object before(Invocation invocation) { // 在这里执行预处理操作 Object parameter = invocation.getArgs(); // 获取参数 // ...你的代码... return parameter; // 返回处理后的参数 } @Override public Object after(Invocation invocation) { // 执行SQL后处理 // ...你的代码... } } ``` 3. **注册拦截器**: 在 Spring Boot 的 MyBatis 配置中,通过 `SqlSessionFactoryBean` 或者 `SqlSessionBuilder` 注册你的拦截器。可以通过 `interceptors` 属性来添加自定义拦截器列表。 ```java @Configuration public class MyBatisConfig { @Bean public SqlSessionFactory sqlSessionFactory(MyBatisMapperScannerConfigurer scannerConfigurer) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setMapperScannerConfigurer(scannerConfigurer); // 添加你的拦截器 factoryBean.setPlugins(Arrays.asList(new YourCustomInterceptor())); return factoryBean.getObject(); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值