step1:定义Interceptor实现org.apache.ibatis.plugin.Interceptor

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Value; import java.util.Properties; /**
* code by me
* <p>
* Data:2017/8/10 Time:11:28
* User:lbh
*/
@Intercepts
({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
})
public class FDNSqlInterceptor implements Interceptor {
private static Log logger = LogFactory.getLog(FDNSqlInterceptor.class); @Value("${fdn.open}")
private boolean fdnOpen; static int MAPPED_STATEMENT_INDEX = 0;// 这是对应上面的args的序号
static int PARAMETER_INDEX = 1;
static int ROWBOUNDS_INDEX = 2;
static int RESULT_HANDLER_INDEX = 3;
@Override
public Object intercept(Invocation invocation) throws Throwable {
if(!fdnOpen){
return invocation.proceed();
}
final Object[] queryArgs = invocation.getArgs();
final MappedStatement mappedStatement = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
final Object parameter = queryArgs[PARAMETER_INDEX];
final BoundSql boundSql = mappedStatement.getBoundSql(parameter); String sql = boundSql.getSql();
if(sql.contains("xx_pro")){
sql = sql.replace("xx_pro","xx_pro_fdn");
} // 重新new一个查询语句对像
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
// 把新的查询放到statement里
MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
for (ParameterMapping mapping : boundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
return invocation.proceed();
} @Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} @Override
public void setProperties(Properties properties) { } private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
builder.keyProperty(ms.getKeyProperties()[0]);
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
} public static class BoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}

step2:在mybatis的配置文件中加入plugin

  <plugins>
<plugin interceptor="xx.interceptor.FDNSqlInterceptor"></plugin>
</plugins>

  

mybatis自定义插件动态修改sql语句的更多相关文章

  1. 自定义函数动态执行SQL语句

    Oracle 动态SQL有两种写法:用 DBMS_SQL 或 execute immediate,建议使用后者. DDL 和 DML Sql代码 收藏代码 /*** DDL ***/ begin EX ...

  2. Mybatis之动态构建SQL语句

    今天一个新同事问我,我知道如何利用XML的方式来构建动态SQL,可是Mybatis是否能够利用注解完成动态SQL的构建呢?!!答案是肯定的,MyBatis 提供了注解,@InsertProvider, ...

  3. MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存

    目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...

  4. MyBatis学习 之 二、SQL语句映射文件(1)resultMap

    目录(?)[-] 二SQL语句映射文件1resultMap resultMap idresult constructor association联合 使用select实现联合 使用resultMap实 ...

  5. mybatis 自定义插件的使用

    今天看了别人的mybatis的教学视频,自己手写了一个简单的自定义的插件,有些细节记录一下. 先看下mybatis的插件的一些说明: MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用. ...

  6. springBoot + mybatis实现执行多条sql语句出错解决方法

    在Idea中执行多条sql语句的修改(mybatis默认的是执行sql语句是执行单条,所以要执行多条的时候需要进行配置) 需要在连接字符串中添加上&allowMultiQueries=true ...

  7. 如何根据实体动态生成sql语句

    该文章同时解决了,如何向数据库中添加Null值,以及如何处理“参数化查询未提供参数”的错误.解决方案请看第二段折叠的代码. 背景: 在项目开发的过程中,往往需要根据实体的值来修改sql语句,比如说,有 ...

  8. Mybatis框架(9)---Mybatis自定义插件生成雪花ID做为表主键项目

    Mybatis自定义插件生成雪花ID做为主键项目 先附上项目项目GitHub地址 spring-boot-mybatis-interceptor 有关Mybatis雪花ID主键插件前面写了两篇博客作为 ...

  9. 模拟Hibernate动态生成SQL语句

    这里有一个xml配置文件,也就是Hibernate框架中会用到的POJO和数据库的映射文件 <?xml version="1.0" encoding="utf-8& ...

随机推荐

  1. Visual stuido 项目路径的奇怪问题

    从别人那里以zip的形式接受了一个solution, 然后在接收目录解压缩,然后剪切到其他的目录.此时报错,说找不到项目文件,看Visual studio 寻找的详细路径,发现它还是到解压缩的那个目录 ...

  2. php 传变量到 js 文件

    php 传变量到 js 文件 // 传变量到js $oncj="taocanonc(".$i.",".$alli.",".$row1[mon ...

  3. 通读Cheerio文档

    前言 cheerio是一款非常实用的nodejs第三方包,适用于服务端(nodejs端)处理html.它有着与jquery及其相似(几乎是一致)的api,速度飞快,使用灵活,而且不仅能够处理html, ...

  4. android中使用toolbar

    系统默认使用的是ActionBar,就是界面中的标题栏,但是由于ActionBar设计的原因,被限定只能位于活动的顶部,从而不能实现Material Design效果,所以官方建议使用Toolbar替 ...

  5. javascript简写精练

    一.算术运算符 var n = 5,v; 1.n = n*5; 2.n*=5; 同 n = n*5 二.条件判断 var b = true; 1.if (!false) { alert('true') ...

  6. Linux安装pear包

    一.安装pear包. 1.安装: $ sudo wget http://pear.php.net/go-pear.phar $ sudo php go-pear.har 2.查看pear下安装的包: ...

  7. DbScopeFactory

    using (var db = DbScopeFactory.Create()) { //这里修改数据 db.SaveChanges(); }

  8. 火狐浏览器flash经常奔溃的

    火狐浏览器flash经常奔溃的 1.首先,在火狐浏览器地址栏在输入:about:config?filter=dom.ipc.plugins.flash.disable-protected-mode,按 ...

  9. Webwork【03】核心类 ServletDispatcher 的初始化

    1. Webwork 与 Xwork 搭建环境需要的的jar 为:webwork-core-1.0.jar,xwork-1.0.jar,搭建webwork 需要xwork 的jar呢?原因是这样的,W ...

  10. Windows下安装Oracle Database 12c Release 1(12.1.0.2.0) - Enterprise Edition

    Windows下安装Oracle Database 12c Release 1(12.1.0.2.0) 最近因需要在Oracle 数据库上建立ODI的资料档案库,需要安装Oracle Database ...