Mybatis系列之自定义SQL拦截器

2022-05-07 16:37:22 浏览数 (1)

本博客介绍的是继承Mybatis提供的Interface接口,自定义拦截器,然后将项目中的sql拦截一下,打印到控制台。

先自定义一个拦截器

代码语言:javascript复制
package com.muses.taoshop.common.core.database.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import java.util.Properties;

/**
 * <pre>
 *  Mybatis SQL拦截器
 * </pre>
 *
 * @author nicky
 * @version 1.00.00
 * <pre>
 * 修改记录
 *    修改后版本:     修改人:  修改日期:     修改内容:
 * </pre>
 */
@Component
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class MybatisSqlInterceptor implements Interceptor {

    Logger  LOGGER = LoggerFactory.getLogger(MybatisSqlInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 拦截sql
        Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        String sql = boundSql.getSql();
        LOGGER.info("获取到的SQL:{}" sql);
        if (StringUtils.isBlank(sql)) {
            return invocation.proceed();
        }
        // 返回
        return invocation.proceed();
    }
 
    @Override
    public Object plugin(Object obj) {
        return Plugin.wrap(obj, this);
    }
 
    @Override
    public void setProperties(Properties arg0) {}

}

然后在SqlSessionFactoryBean进行配置,主要代码factoryBean.setPlugins(new Interceptor[]{mybatisSqlInterceptor}); 下面是我的Mybatis配置类,是基于SpringBoot做的,仅供参考

代码语言:javascript复制
package com.muses.taoshop.common.core.database.config;

import com.muses.taoshop.common.core.database.annotation.MybatisRepository;
import com.muses.taoshop.common.core.database.annotation.TypeAliasesPackageScanner;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;

import static com.muses.taoshop.common.core.database.config.BaseConfig.*;

/**
 * <pre>
 *  Mybatis配置类
 * </pre>
 *
 * @author nicky
 * @version 1.00.00
 * <pre>
 * 修改记录
 *    修改后版本:     修改人:  修改日期:     修改内容:
 * </pre>
 */
@MapperScan(
        basePackages = MAPPER_PACKAGES,
        annotationClass = MybatisRepository.class,
        sqlSessionFactoryRef = SQL_SESSION_FACTORY
)
@ComponentScan
@EnableTransactionManagement
@Configuration
public class MybatisConfig {


    @Autowired
    MybatisSqlInterceptor mybatisSqlInterceptor;

    TypeAliasesPackageScanner packageScanner = new TypeAliasesPackageScanner();

    @Bean(name = DATA_SOURCE_NAME)
    @ConfigurationProperties(prefix = DATA_SOURCE_PROPERTIES)
    @Primary
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = SQL_SESSION_FACTORY)
    public SqlSessionFactory sqlSessionFactory(@Qualifier(DATA_SOURCE_NAME)DataSource dataSource)throws Exception{
        //SpringBoot默认使用DefaultVFS进行扫描,但是没有扫描到jar里的实体类
        VFS.addImplClass(SpringBootVFS.class);
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setPlugins(new Interceptor[]{mybatisSqlInterceptor});
        factoryBean.setDataSource(dataSource);
        //factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try{
            factoryBean.setMapperLocations(resolver.getResources("classpath*:/mybatis/*Mapper.xml"));
            String typeAliasesPackage = packageScanner.getTypeAliasesPackages();
            factoryBean.setTypeAliasesPackage(typeAliasesPackage);
            SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
            return sqlSessionFactory;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Bean(name = MYBATIS_TRANSACTION_MANAGER)
    public DataSourceTransactionManager transactionManager(@Qualifier(DATA_SOURCE_NAME)DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


}

项目执行之后,在控制台就可以看到打印的sql,sql执行被拦截下来

代码语言:javascript复制
2018-12-17 10:43:10.728  INFO 4428 --- [nio-8081-exec-1] c.m.t.c.c.d.c.MybatisSqlInterceptor      :
 获取到的SQL:{} SELECT 
    id,
        category_name as categoryName,
        sjid,
        last_modify_time as lastModifyTime,
        create_time as createTime
        FROM item_category t

0 人点赞