MybatisPlusInterceptor实现sql拦截器(超详细)
MyBatis-Plus 提供了插件接口 MybatisPlusInterceptor,用于拦截 MyBatis 的相关操作,例如 SQL 查询、插入、更新、删除等。
以下是一个简单的 MyBatisPlusInterceptor 实现示例,用于拦截并修改 SQL 语句:
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties;
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MyInterceptor extends MybatisPlusInterceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 获取StatementHandler,实际处理者
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
// 获得SQL
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
System.out.println("Original SQL: " + sql);
// 修改SQL
String modifiedSql = modifySql(sql);
System.out.println("Modified SQL: " + modifiedSql);
// 反射修改SQL
Field sqlField = boundSql.getClass().getDeclaredField("sql");
sqlField.setAccessible(true);
sqlField.set(boundSql, modifiedSql);
// 继续执行
return invocation.proceed();
}
private String modifySql(String originalSql) {
try {
// 解析SQL
PlainSelect plainSelect = (PlainSelect) CCJSqlParserUtil.parse(originalSql);
// 添加额外条件
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(new Column("字段名"));
equalsTo.setRightExpression(new StringValue("条件值"));
AndExpression andExpression = new AndExpression(equalsTo);
plainSelect.setWhere(andExpression);
// 生成修改后的SQL
return plainSelect.toString()
评论已关闭