mybatis - 基于拦截器修改执行中的SQL语句

拦截器介绍

mybatis提供了@Intercepts注解允许开发者对mybatis的执行器Executor进行拦截。
Executor接口方法主要有update、query、commit、rollback等等。
主要思路为:

  1. 进入拦截器方法中
  2. 获取拦截器方法参数
  3. 获取解析参数及SQL
  4. 自定义生成自己的SQL语句
  5. 将自定义SQL设置进参数中
  6. 由mybatis处理后续问题

    拦截器代码

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
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.Plugin;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Properties;
@Component
@Intercepts({@org.apache.ibatis.plugin.Signature(type = Executor.class, method = "query",
        args = {
        MappedStatement.class,
                Object.class,
                RowBounds.class,
                ResultHandler.class,
                CacheKey.class,
                BoundSql.class})})
public class MybatisInterceptorConfig implements Interceptor {
     /*自定义SQL*/
     private String resetSql(String sql) {

     }
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        resetSql(invocation);
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }
    @Override
    public void setProperties(Properties properties) {

    }
    private void resetSql(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        BoundSql boundSql = (BoundSql) args[5];
        if(StringUtils.isNotEmpty(boundSql.getSql())) {
            modify(boundSql,"sql",resetSql(boundSql.getSql()));
        }
    }
    private static void modify(Object object, String fieldName, Object newFieldValue){
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            if(!field.isAccessible()) {
                field.setAccessible(true);
            }
            field.set(object, newFieldValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原文地址:https://www.cnblogs.com/cjunn/p/12168421.html

时间: 2024-08-29 03:34:18

mybatis - 基于拦截器修改执行中的SQL语句的相关文章

Mybatis之拦截器--获取执行SQL实现多客户端数据同步

最近的一个项目是将J2EE环境打包安装在客户端(使用 nwjs + NSIS 制作安装包)运行, 所有的业务操作在客户端完成, 数据存储在客户端数据库中. 服务器端数据库汇总各客户端的数据进行分析. 其中客户端ORM使用Mybatis. 通过Mybatis拦截器获取所有在执行的SQL语句, 定期同步至服务器. 本文通过在客户端拦截SQL的操作介绍Mybatis拦截器的使用方法. 1. 项目需求 客户分店较多且比较分散, 部分店内网络不稳定, 客户要求每个分店在无网络的情况下也能正常使用系统, 同

springmvc中自定义拦截器以及拦截器的执行过程

1.拦截器在一次请求中的执行流程 2.拦截器入门案例 2.1springMVC.xml的编写 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m

Mybatis Interceptor 拦截器原理 源码分析

Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最好了解下它的原理,以便写出安全高效的插件. 代理链的生成 Mybatis支持对Executor.StatementHandler.PameterHandler和ResultSetHandler进行拦截,也就是说会对这4种对象进行代理. 通过查看Configuration类的源代码我们可以看到,每次都

SpringMVC多拦截器的执行

如果有多个拦截器,执行的顺序是在SpringMVC的配置文件里的前后顺序. <mvc:interceptors> <bean class="com.neuedu.interceptor.Inteceptor1"></bean> <mvc:interceptor> <mvc:mapping path="/test"/> <bean class="com.neuedu.interceptor.I

如何在sqlplus中查看、修改、执行缓存的SQL语句

在sqlplus中,如果没有上下翻页工具,sqlplus是不能向Linux终端一样上下翻历史命令的,但sqlplus会记录最近的一行DML语句到buffer中,我们可以使用一些简单的命令查看.修改.执行记录在buffer中的语句,如下: l[ist] [n] 查看buf中的SQL: del [n] 移除buf中的某行SQL: cl[ear] buff[er] 移除buf中语句: C[hange]/old_value/new_value 表示更改第一个出现的字符 : 此外,还有I和A,分别表示:

mysql+mybatis 在mybatis一个标签中,执行多条sql语句

然后在mybatis映射文件中的标签中,一般不能执行多条sql,如下: <insert id="addUser" parameterType="User" > insert into t_users (name,password,phone) values (#{name}, #{password},#{phone}); insert into t_dep (depname) values (#{depname}) </insert> MyS

MyBatis一次执行多条SQL语句

MyBatis一次执行多条SQL语句 有个常见的场景:删除用户的时候需要先删除用户的外键关联数据,否则会触发规则报错. 解决办法不外乎有三个:1.多条sql分批执行:2.存储过程或函数调用:3.sql批量执行. 今天我要说的是MyBatis中如何一次执行多条语句(使用mysql数据库). 1.修改数据库连接参数加上allowMultiQueries=true,如: hikariConfig.security.jdbcUrl=jdbc:mysql://xx.xx.xx:3306/xxxxx?cha

sqlserver 存储过程中拼接sql语句 动态执行

ALTER PROC [dbo].[Student_Friend_Get] @startRowIndexId INT, @maxNumberRows INT, @schoolId INT, @gradeId INT, @cId INT, @keyWords NVARCHAR(100), @userName VARCHAR(50) AS BEGIN DECLARE @sqlfilter VARCHAR(max) SET @sqlfilter = ' ' IF(@schoolId <> -1) S

MyBatis中动态SQL语句完成多条件查询

http://blog.csdn.net/yanggaosheng/article/details/46685565 MyBatis中动态SQL语句完成多条件查询 <select id="queryEmp"  resultType="cn.test.entity.Emp"> select * from emp where 1=1 <if test="deptNo!=null"> and deptno=#{deptNO} &