java执行sql语句修改_mybatis - 基于拦截器修改执行中的SQL语句

该博客介绍了如何使用MyBatis的@Intercepts注解来拦截Executor接口的query方法,通过获取并修改SQL语句,实现自定义SQL的功能。在拦截器中,作者展示了如何获取和设置BoundSql对象的SQL内容,并利用反射技术修改final字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拦截器介绍

mybatis提供了@Intercepts注解允许开发者对mybatis的执行器Executor进行拦截。

Executor接口方法主要有update、query、commit、rollback等等。

主要思路为:

进入拦截器方法中

获取拦截器方法参数

获取解析参数及SQL

自定义生成自己的SQL语句

将自定义SQL设置进参数中

由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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值