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";
        }
    }
}
相关推荐
程序员张312 分钟前
Maven编译和打包插件
java·spring boot·maven
灵犀学长2 小时前
EasyExcel之SheetWriteHandler:解锁Excel写入的高阶玩法
spring boot·excel
zwjapple2 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
tan180°4 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
DuelCode5 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
优创学社25 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理5 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
猴哥源码5 小时前
基于Java+springboot 的车险理赔信息管理系统
java·spring boot
爬山算法7 小时前
MySQL(116)如何监控负载均衡状态?
数据库·mysql·负载均衡
Code blocks7 小时前
使用Jenkins完成springboot项目快速更新
java·运维·spring boot·后端·jenkins