Mybatis自定义SQL拦截器

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

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

先自定义一个拦截器

    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做的,仅供参考

    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);
        }

    }

来源:https://www.cnblogs.com/mzq123

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » Mybatis自定义SQL拦截器

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏