springboot项目中MyBatis自定义拦截器

mybatis实现拦截器需要使用它自有的Interceptor接口和@Intercepts注解

  1. Interceptor接口中包含三个方法:

    • intercept:主要是写我们具体业务逻辑,比如针对增删改sql语句添加更新日期。
    • plugin:生成代理对象
    • setProperties:设置拦截器属性
  2. @Intercepts

    作用:声明这是一个拦截器。

    属性:Signature(注解)

    @Signature:要拦截的具体方法

    ​ 属性: type-拦截接口(四种类型,具体看官网 https://mybatis.net.cn/configuration.html#plugins ),method-拦截的方法(update,insert,select),args-重载时根据参数列表确定要拦截的方法

简单代码实现:

import org.apache.ibatis.executor.Executor;
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.springframework.stereotype.Component;
import java.util.Properties;
@Component
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class MyBatisIntercept implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
/**
* 业务逻辑,例如:
* 在修改时进行修改时间的插入
*/
return null;
}
@Override
public Object plugin(Object target) {
/**
* 生产代理对象
*/
return null;
}
@Override
public void setProperties(Properties properties) {
/**
* 设置拦截器的属性
*/
}
}

声明完拦截器后需要将其装入mybatis中:

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class MyBatisConfig {
@Autowired
private MyBatisIntercept myBatisIntercept;
@Autowired
private DataSource dataSource;
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//将自定义拦截器装入mybatis
bean.setDataSource(dataSource);
bean.setPlugins(myBatisIntercept);
return bean;
}
}
posted @   plum_wink  阅读(1914)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
点击右上角即可分享
微信分享提示