springboot mybatis 动态修改sql
·
拦截器
import cn.hutool.core.util.ReflectUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.springframework.util.CollectionUtils;
import java.sql.Connection;
import java.util.Set;
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class TablePrefixInterceptor implements Interceptor {
private TableProperties properties;
public TablePrefixInterceptor(TableProperties properties) {
this.properties = properties;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 获取StatementHandler,这里进行具体的拦截操作
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
// 通过反射获取原始SQL
String originalSql = (String) ReflectUtil.getFieldValue(boundSql, "sql");
String prefix = properties.getPrefix();
Set<String> tableNames = properties.getTableNames();
String lowerCase = originalSql.toLowerCase();
// 根据逻辑判断是否需要添加前缀,这里以某个条件为例
if (StringUtils.isNotBlank(originalSql) && !CollectionUtils.isEmpty(tableNames)) {
for (String tableName : tableNames) {
if (lowerCase.contains(tableName.toLowerCase())) {
// 替换原始SQL中的表名,添加前缀
String modifiedSql = originalSql.replace(tableName, prefix + tableName);
// 通过反射设置修改后的SQL
ReflectUtil.setFieldValue(boundSql, "sql", modifiedSql);
break;
}
}
}
// 继续执行后续操作
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
}
注册拦截器
@Configuration
public class DataSourceConfig {
@Autowired
private TableProperties properties;
@Primary
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setPlugins(new TablePrefixInterceptor(properties));
return bean.getObject();
}
配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Set;
@Component
@ConfigurationProperties(prefix = "**")
@Data
public class TableProperties {
private String prefix;
private Set<String> tableNames;
}
加入配置:
xxx:
prefix: test.
tableNames:
- test_tt
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)