Mybatis同时支持多种数据库(oracle 和MySQL)


这里说下对多种数据库的支持,不是多个数据源。

这里要用到mybatis的databaseId。如下:

<select id="isExist" resultType="Boolean" databaseId="mysql">
    SELECT EXISTS(SELECT 1 FROM `${db}`.test_table WHERE table_id=#{tableId} LIMIT 1)
</select>

<select id="isExist" resultType="Boolean" databaseId="oracle">
    SELECT COUNT(*) FROM ${db}."test_table " WHERE "table_id"=#{tableId}
</select>

在mapper.xml中加上databaseId就可以指定要用的sql,mybatis会根据链接过来的DataSource自动识别。

我这里使用的是spring boot,加上一个bean的配置:

    /**
     * 自动识别使用的数据库类型
     * 在mapper.xml中databaseId的值就是跟这里对应,
     * 如果没有databaseId选择则说明该sql适用所有数据库
     * */
    @Bean
    public DatabaseIdProvider getDatabaseIdProvider(){
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("Oracle","oracle");
        properties.setProperty("MySQL","mysql");
        properties.setProperty("DB2","db2");
        properties.setProperty("Derby","derby");
        properties.setProperty("H2","h2");
        properties.setProperty("HSQL","hsql");
        properties.setProperty("Informix","informix");
        properties.setProperty("MS-SQL","ms-sql");
        properties.setProperty("PostgreSQL","postgresql");
        properties.setProperty("Sybase","sybase");
        properties.setProperty("Hana","hana");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }

我这里列出了所有支持的数据库类型,实际使用的时候根据自己要用的数据库添加就好。

在配置文件中正常配置数据库信息就可以了。

如果使用的时候有问题,在配置文件中加上下边配置

database:
  type: oracle

#mybatis设置
mybatis:
  mapper-locations: classpath*:mapper/*.xml
  configuration:
    database-id: ${database.type}
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

主要是database-id这个 。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

转载来着 https://blog.csdn.net/qq_35981283/article/details/79503571


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM