liusheng
12 小时以前 c62e26954e41360fc6a2efc874815aa84f8b0073
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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) {
        // 不需要设置属性
    }