package com.ruoyi.common.mybatis; 
 | 
  
 | 
import com.ruoyi.common.utils.SqlConverter; 
 | 
import com.ruoyi.common.utils.SpringContextUtils; 
 | 
import org.apache.ibatis.executor.statement.StatementHandler; 
 | 
import org.apache.ibatis.plugin.*; 
 | 
import org.springframework.stereotype.Component; 
 | 
  
 | 
import java.sql.Connection; 
 | 
import java.util.Properties; 
 | 
  
 | 
/** 
 | 
 * SQL转换拦截器 
 | 
 */ 
 | 
@Component 
 | 
@Intercepts({ 
 | 
    @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}) 
 | 
}) 
 | 
public class SqlConverterInterceptor implements Interceptor { 
 | 
  
 | 
    private SqlConverter sqlConverter; 
 | 
  
 | 
    @Override 
 | 
    public Object intercept(Invocation invocation) throws Throwable { 
 | 
        if (sqlConverter == null) { 
 | 
            if (SpringContextUtils.getContext() == null) { 
 | 
                // Spring容器还没初始化,直接跳过转换 
 | 
                return invocation.proceed(); 
 | 
            } 
 | 
            sqlConverter = SpringContextUtils.getBean(SqlConverter.class); 
 | 
        } 
 | 
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); 
 | 
        String sql = statementHandler.getBoundSql().getSql(); 
 | 
         
 | 
        // 转换SQL 
 | 
        String convertedSql = sqlConverter.convertSql(sql); 
 | 
         
 | 
        // 使用反射设置转换后的SQL 
 | 
        java.lang.reflect.Field field = statementHandler.getBoundSql().getClass().getDeclaredField("sql"); 
 | 
        field.setAccessible(true); 
 | 
        field.set(statementHandler.getBoundSql(), convertedSql); 
 | 
         
 | 
        return invocation.proceed(); 
 | 
    } 
 | 
  
 | 
    @Override 
 | 
    public Object plugin(Object target) { 
 | 
        return Plugin.wrap(target, this); 
 | 
    } 
 | 
  
 | 
    @Override 
 | 
    public void setProperties(Properties properties) { 
 | 
        // 不需要设置属性 
 | 
    } 
 | 
}  
 |