spring boot Mybatis 拦截器实现拼接sql和修改的代码详解

定义一个 SqlIntercepor 类

import com.culturalCenter.placeManage.globalConfig.Interface.InterceptAnnotation;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Statement;
import java.util.Properties;
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Component
@Configuration
public class SqlInterceptor implements Interceptor {
    private Logger logger = LoggerFactory.getLogger(SqlInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
        //先拦截到RoutingStatementHandler,里面有个StatementHandler类型的delegate变量,其实现类是BaseStatementHandler,然后就到BaseStatementHandler的成员变量mappedStatement
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        //id为执行的mapper方法的全路径名,如com.uv.dao.UserMapper.insertUser
        String id = mappedStatement.getId();
        logger.info("拦截到当前请求方法的全路径名为--->:  " + id);
        //sql语句类型 select、delete、insert、update
        String sqlCommandType = mappedStatement.getSqlCommandType().toString();
        BoundSql boundSql = statementHandler.getBoundSql();
        //获取到原始sql语句
        String sql = boundSql.getSql();
        String mSql = sql;
        //获取参数
        Object parameter = statementHandler.getParameterHandler().getParameterObject();
        logger.info("拦截到当前请求SQL为--->: " + sql + "<------------>请求类型为:  " + sqlCommandType);
        logger.info("拦截到当前请求参数为--->: " + parameter);
        //TODO 修改位置
        //注解逻辑判断  添加注解了才拦截//InterceptAnnotation
        Class<?> classType = Class.forName(mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf(".")));
        String mName = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf(".") + 1, mappedStatement.getId().length());
        for (Method method : classType.getDeclaredMethods()) {
            if (method.isAnnotationPresent(InterceptAnnotation.class) && mName.equals(method.getName())) {
                InterceptAnnotation interceptorAnnotation = method.getAnnotation(InterceptAnnotation.class);
                if (interceptorAnnotation.flag()) {
                    mSql = sql + " limit 2";
                }
            }
        }
        //通过反射修改sql语句
        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql, mSql);
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, new SqlInterceptor());
    }
    @Override
    public void setProperties(Properties properties) {
//        this.setProperties(properties);
    }

自定义一个注解类实现局部处理SQL修改

InterceptAnnotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 配合SqlInterceptor实现局部拦截
 * */
@Target({ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface InterceptAnnotation {
    boolean flag() default  true;
}

自定义数据源工厂类

SqlSessionFactoryConfig

package com.culturalCenter.placeManage.globalConfig;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
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 org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
 * @author wulincheng
 * @Date 2020年6月23日18:25:22
 *  创建SQL连接工厂类
 * */
@Configuration
public class SqlSessionFactoryConfig {
    @javax.annotation.Resource
    DruidDataSource dataSource;
    /**
     * @Autowired SqlSessionFactory sqlSessionFactory;
     * SqlSession session = sqlSessionFactory.openSession();
     * //创建sqlMapper
     * SqlMapper sqlMapper = new SqlMapper(session);
     */
    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);//更多参数请自行注入
        bean.setPlugins(new Interceptor[]{new SqlInterceptor()});
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/*.xml");
        bean.setMapperLocations(resources);
        return bean.getObject();
    }
}

到此这篇关于spring boot Mybatis 拦截器,实现拼接sql和修改的文章就介绍到这了,更多相关spring boot Mybatis 拦截器内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot整合mybatis分页拦截器的问题小结

    简介 又到了吹水时间,是这样的,今天开发时想将自己写好的代码拿来优化,因为不想在开发服弄,怕搞坏了到时候GIT到生产服一大堆问题,然后把它分离到我轮子(工具)项目上,最后运行后发现我获取List的时候很卡至少10秒,我惊了平时也就我的正常版本是800ms左右(不要看它很久,因为数据量很大,也很正常.),前提是我也知道很慢,就等的确需要优化时,我在放出我优化的plus版本,回到10秒哪里,最开始我刚刚接到这个app项目时,在我用 PageHelper.startPage(page, num);(分

  • springboot+mybatis-plus基于拦截器实现分表的示例代码

    目录 前言 一.设计思路 二.实现思路 三.代码实现 接口描述 核心组成部分 1.本地线程工具类 2.注解部分 3.拦截器实现 四.测试 后记 前言 最近在工作遇到数据量比较多的情况,单表压力比较大,crud的操作都受到影响,因为某些原因,项目上没有引入sharding-jdbc这款优秀的分表分库组件,所以打算简单写一个基于mybatis拦截器的分表实现 一.设计思路 在现有的业务场景下,主要实现的目标就是表名的替换,需要解决的问题有 如何从执行的方法中,获取对应的sql并解析获取当前执行的表名

  • springboot配置多数据源后mybatis拦截器失效的解决

    目录 1. 解析配置文件初始化数据源 2. 定义数据源枚举类型 3. TheadLocal保存数据源类型 4. 自定义sqlSessionProxy 5. 自定义路由 6. 定义切面,dao层定义切面 7. 最后在写库增加事务管理 8. 在配置文件中增加数据源配置 配置文件是通过springcloudconfig远程分布式配置.采用阿里Druid数据源.并支持一主多从的读写分离.分页组件通过拦截器拦截带有page后缀的方法名,动态的设置total总数. 1. 解析配置文件初始化数据源 @Conf

  • Springboot自定义mybatis拦截器实现扩展

    前言 相信大家对拦截器并不陌生,对mybatis也不陌生. 有用过pagehelper的,那么对mybatis拦截器也不陌生了,按照使用的规则触发sql拦截,帮我们自动添加分页参数 . 那么今天,我们的实践 自定义mybatis拦截器也是如此, 本篇文章实践的效果: 针对一些使用 单个实体类去接收返回结果的 mapper方法,我们拦截检测,如果没写 LIMIT 1 ,我们将自动帮忙填充,达到查找单条数据 效率优化的效果. ps: 当然,跟着该篇学会了这个之后,那么可以扩展的东西就多了,大家按照自

  • SpringBoot整合Mybatis自定义拦截器不起作用的处理方案

    目录 SpringBoot整合Mybatis自定义拦截器不起作用 1. 原始的读取mybatis-config.xml文件 2. 与SpringBoot容器整合 2.1 mybatis的自动装载 3. 在mybatis-config.xml配置又放入Spring容器 SpringBoot 自定义Mybatis拦截器 第一种 第二种 第三种 SpringBoot整合Mybatis自定义拦截器不起作用 Mybatis插件生效的方式: 1. 原始的读取mybatis-config.xml文件 该方式和

  • spring boot Mybatis 拦截器实现拼接sql和修改的代码详解

    定义一个 SqlIntercepor 类 import com.culturalCenter.placeManage.globalConfig.Interface.InterceptAnnotation; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedSta

  • spring boot加入拦截器Interceptor过程解析

    这篇文章主要介绍了spring boot加入拦截器Interceptor过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.spring boot拦截器默认有 HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationInterceptor LocaleChangeInterceptor ThemeChangeInterceptor 2.配置spring

  • spring boot的拦截器简单使用示例代码

    1.spring boot拦截器默认有: HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationInterceptor LocaleChangeInterceptor ThemeChangeInterceptor 其中 LocaleChangeInterceptor 和 ThemeChangeInterceptor 比较常用. 2.实现自定义拦截器只需要3步: 1).创建我们自己的拦截器类并实现 Handler

  • spring boot配置拦截器代码实例

    这篇文章主要介绍了spring boot配置拦截器代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 首先引入web模块的依赖: 复制代码 <!-- spring boot web 组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</ar

  • Spring Boot配置拦截器及实现跨域访问的方法

    拦截器功能强大,能够深入方法前后,常应用于日志记录.权限检查和性能检测等,几乎是项目中不可或缺的一部分,本文就来实现Spring Boot自定义拦截器的配置. 理论指导 问:Spring Boot怎么配置拦截器? 答:配置一个拦截器需要两步完成. 自定义拦截器,实现HandlerInterceptor这个接口.这个接口包括三个方法,preHandle是请求执行前执行的,postHandler是请求结束执行的,但只有preHandle方法返回true的时候才会执行,afterCompletion是

  • spring boot使用拦截器修改请求URL域名 换 IP 访问的方法

    目录 Interceptor 介绍 Interceptor 作用 自定义 Interceptor 案例1 :域名换IP访问 案例2: erverWebExchange通过拦截器修改请求url 案例3: 将请求路径中/idea都去掉 案例4: SpringBoot 利用过滤器Filter修改请求url地址 案例5.拦截器: WebMvcConfigurerAdapter拦截器 结语 Interceptor 介绍 拦截器(Interceptor)同 Filter 过滤器一样,它俩都是面向切面编程——

  • 如何在Spring Boot应用中优雅的使用Date和LocalDateTime的教程详解

    Java8已经发布很多年了,但是很多人在开发时仍然坚持使用着Date和SimpleDateFormat进行时间操作.SimpleDateFormat不是线程安全的,而Date处理时间很麻烦,所以Java8提供了LocalDateTime.LocalDate和LocalTime等全新的时间操作API.无论是Date还是LocalDate,在开发Spring Boot应用时经常需要在每个实体类的日期字段上加上@DateTimeFormat注解来接收前端传值与日期字段绑定,加上@JsonFormat注

  • spring boot 注册拦截器过程详解

    拦截器是动态拦截Action调用的对象.它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重用部分的方式.在AOP(Aspect-Oriented Programming)中拦截器用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作. 如何在spring boot中添加拦截器? 1.首先自己实现一个拦截器 import org.springframework.web.ser

  • Spring Boot集成Shiro并利用MongoDB做Session存储的方法详解

    前言 shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/ 它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和shiro整合的功能! 之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mongodb中,这个比较符合mongodb的设计初衷,而且在分布式项目中mongo

  • Spring Boot编写拦截器教程实例解析

    创建一个类并使其实现接口HandlerInterceptor 接口提供了一个请求的三个周期的拦截方法 在controller之前,返回true则放行,false反之,handler包含处理请求的controller类以及其方法 boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 在controller接受请求之后,contorller渲染视图之前,如果发生异常就不执

随机推荐