51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

MybatisPlus拦截并修改SQL语句

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        &lt;!--mybatis-plus扩展,用于sql拦截--&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.baomidou&lt;/groupId&gt;
            &lt;artifactId&gt;mybatis-plus-extension&lt;/artifactId&gt;
            &lt;version&gt;3.4.1&lt;/version&gt;
        &lt;/dependency&gt;</code></pre>



 
```lang-java
@Slf4j
@Component
@AllArgsConstructor
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor {

    private DataSource dataSource;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        this.sqlParser(metaObject);
        // 先判断是不是INSERT操作 不是直接过滤
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        // 执行的SQL语句
        String originalSql = boundSql.getSql();
        // SQL语句的参数
        Object parameterObject = boundSql.getParameterObject();
        originalSql = originalSql.replace("insert", "upsert")
                .replace("INSERT", "UPSERT");
        metaObject.setValue("delegate.boundSql.sql", originalSql);
        return invocation.proceed();
    }

}

```


 
```lang-java
@Configuration
public class MybatisPlusConfig {
    @Bean
    @ConditionalOnMissingBean
    public DataScopeInterceptor dataScopeInterceptor(DataSource dataSource) {
        return new DataScopeInterceptor(dataSource);
    }
}

```


赞(0)
未经允许不得转载:工具盒子 » MybatisPlus拦截并修改SQL语句