springboot适配mybatis+guassdb与Mysql兼容性问题处理

我们在做一些兼容非MySQL数据库时,经常遇到一些关键字,或者语法差异问题。 这里举个极端例子,有个字段为desc,因为与数据库关键字冲突,在mysql中需要使用`desc`,而guassdb中需要使用"desc"

针对有语法差异的,利用mybatis的@Intercepts注解插件拦截,在拦截器中,处理与mysql的兼容性问题,通过类型判断,写不同逻辑

java 复制代码
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;


@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))
public class SqlDialectInterceptor implements Interceptor {

    private String databaseType;

    public SqlDialectInterceptor(String databaseType) {
        this.databaseType = databaseType;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        String adjustedSql = adjustedSql(sql);
        Field sqlField = boundSql.getClass().getDeclaredField("sql");
        sqlField.setAccessible(true);
        sqlField.set(boundSql, adjustedSql);
        return invocation.proceed();
    }

    private String adjustedSql(String sql) {
        if (databaseType.toLowerCase().contains("mysql")) {
            sql = sql.replace("\"desc\"", "`desc`");
        } else {
            sql = sql.replace("`desc`", "\"desc\"");
        }
        return sql;
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
java 复制代码
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;


@Configuration
@MapperScan(basePackages = "com.db.mapper")
public class SqlSessionFactoryConfig {

    private static final Logger loggder = LoggerFactory.getLogger(SqlSessionFactoryConfig.class);

    private final DataSource dataSource;

    public SqlSessionFactoryConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public SqlSessionFactoryBean createSqlSessionFactory() {
        try {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            String packageXmlConfigPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "mybatis/mapper/**/*.xml";
            // 设置 mapper 配置文件路径
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageXmlConfigPath));
            // 设置数据源
            sqlSessionFactoryBean.setDataSource(dataSource);
            // 设置 mybatis 配置文件路径
            sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
            sqlSessionFactoryBean.setPlugins(new SqlDialectInterceptor(getDatabaseType(dataSource)));
            return sqlSessionFactoryBean;
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    private String getDatabaseType(DataSource dataSource) {
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            String databaseProductName = metaData.getDatabaseProductName();
            loggder.info("init getDatabaseType: {}", databaseProductName);
            return databaseProductName;
        } catch (Exception ex) {
            loggder.info("init getDatabaseType error {}", ex.getMessage(), ex);
            return "mysql";
        }
    }
}
相关推荐
睡觉待开机10 分钟前
0. MySQL在Centos 7环境安装
数据库·mysql·centos
一叶知秋哈39 分钟前
Java应用Flink CDC监听MySQL数据变动内容输出到控制台
java·mysql·flink
sclibingqing1 小时前
SpringBoot项目接口集中测试方法及实现
java·spring boot·后端
pp-周子晗(努力赶上课程进度版)2 小时前
【MySQL】视图、用户管理、MySQL使用C\C++连接
数据库·mysql
KK溜了溜了3 小时前
JAVA-springboot log日志
java·spring boot·logback
超级小忍3 小时前
如何配置 MySQL 允许远程连接
数据库·mysql·adb
吹牛不交税4 小时前
sqlsugar WhereIF条件的大于等于和等于查出来的坑
数据库·mysql
Java水解4 小时前
MySQL DQL全面解析:从入门到精通
后端·mysql
我命由我123454 小时前
Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题
java·开发语言·spring boot·redis·后端·java-ee·intellij-idea