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";
        }
    }
}
相关推荐
韩立学长几秒前
【开题答辩实录分享】以《自然灾害隐患点管理信息系统》为例进行答辩实录分享
数据库·spring boot
我命由我123454 分钟前
Spring Cloud - Spring Cloud 注册中心与服务提供者(Spring Cloud Eureka 概述、微服务快速入门、微服务应用实例)
java·spring boot·spring·spring cloud·微服务·eureka·java-ee
tryxr42 分钟前
MySQL 之索引为什么选择B+树
数据库·mysql·b+树·索引
一线大码1 小时前
SpringBoot 优雅实现接口的多实现类方式
java·spring boot·后端
Q_Q19632884752 小时前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
摇滚侠2 小时前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 属性优先级 行内写法 变量选择 笔记42
java·spring boot·笔记
摇滚侠2 小时前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 总结 热部署 常用配置 笔记44
java·spring boot·笔记
十年小站2 小时前
一、新建一个SpringBoot3项目
java·spring boot
程序员阿达2 小时前
开题报告之基于SpringBoot框架的路面故障信息上报系统设计与实现
java·spring boot·后端
哞哞不熬夜3 小时前
JavaEE--SpringIoC
java·开发语言·spring boot·spring·java-ee·maven